在PHP中,可以使用MySQLi或PDO扩展来查询数据库中的数据。以下是两种方法的示例:
方法1:使用MySQLi扩展
mydb
的数据库的示例:$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "mydb";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
mysqli_query()
函数执行SQL查询,并获取结果:$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// 输出数据
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 结果";
}
mysqli_close($conn);
方法2:使用PDO扩展
mydb
的数据库的示例:$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "mydb";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
PDO::query()
方法执行SQL查询,并获取结果:$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->rowCount() > 0) {
// 输出数据
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 结果";
}
$conn = null;
以上示例展示了如何使用MySQLi和PDO扩展在PHP中查询数据库数据。请根据您的实际情况修改代码中的数据库连接信息和SQL查询。