要查詢數(shù)據(jù)庫并顯示內(nèi)容,可以使用PHP中的MySQLi擴展或PDO擴展。以下是一個簡單的示例:
使用MySQLi擴展:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// 創(chuàng)建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接是否成功
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
// 查詢數(shù)據(jù)
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 輸出數(shù)據(jù)
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 結(jié)果";
}
$conn->close();
?>
使用PDO擴展:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, name, email FROM users");
$stmt->execute();
// 設(shè)置結(jié)果集為關(guān)聯(lián)數(shù)組
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $row) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
無論使用MySQLi擴展還是PDO擴展,都需要替換示例中的主機名、用戶名、密碼和數(shù)據(jù)庫名以及查詢的數(shù)據(jù)表和字段名稱。