要在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