在PHP中,使用MySQLi或PDO扩展来连接和操作MySQL数据库。这里我将分别展示如何使用MySQLi和PDO的fetch
方法获取数据。
使用MySQLi:
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出每行数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 结果";
}
$conn->close();
使用PDO:
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
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();
}
$sql = "SELECT id, name, email FROM users";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($result)) {
// 输出每行数据
foreach ($result as $row) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 结果";
}
$conn = null;
以上示例展示了如何使用MySQLi和PDO的fetch
方法从MySQL数据库中获取数据。注意,为了简洁起见,我没有在这里展示如何创建和填充数据库表。在实际应用中,你需要先创建一个包含数据的表。