在PHP中,使用foreach
遍歷MySQL視圖數據的方法如下:
view_name
的視圖:CREATE VIEW view_name AS
SELECT column1, column2, column3
FROM table_name
WHERE condition;
<?php
// 數據庫連接信息
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 查詢視圖數據
$sql = "SELECT * FROM view_name";
$result = $conn->query($sql);
// 使用foreach遍歷結果集
if ($result->num_rows > 0) {
// 輸出每行數據
foreach($result as $row) {
echo "column1: " . $row["column1"] . " - column2: " . $row["column2"] . " - column3: " . $row["column3"] . "<br>";
}
} else {
echo "0 results";
}
// 關閉連接
$conn->close();
?>
這段代碼首先連接到MySQL數據庫,然后執行查詢以獲取視圖數據。接著,使用foreach
循環遍歷結果集,并輸出每一行數據。最后,關閉數據庫連接。