要在PHP中使用foreach
遍历MySQL结果集,请按照以下步骤操作:
foreach
循环遍历结果集。以下是一个使用MySQLi的示例:
<?php
// 1. 连接数据库
$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);
}
// 2. 执行查询
$sql = "SELECT id, name FROM your_table";
$result = $conn->query($sql);
// 3. 使用foreach遍历结果集
if ($result->num_rows > 0) {
foreach ($result as $row) {
echo "id: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "0 结果";
}
// 4. 关闭连接
$conn->close();
?>
以下是一个使用PDO的示例:
<?php
// 1. 连接数据库
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
// 2. 执行查询
$sql = "SELECT id, name FROM your_table";
$result = $conn->query($sql);
// 3. 设置结果集为关联数组
$result->setFetchMode(PDO::FETCH_ASSOC);
// 4. 使用foreach遍历结果集
foreach ($result as $row) {
echo "id: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
// 5. 关闭连接
$conn = null;
?>
这两个示例都会输出类似以下内容:
id: 1 - Name: John
id: 2 - Name: Jane
id: 3 - Name: Doe