在PHP中,顯示數據庫內容的方法有以下幾種:
mysqli
或PDO
擴展來連接到數據庫、執行查詢語句并獲取結果集,并使用循環遍歷結果集中的數據。$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM tablename";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "
";
}
} else {
echo "0 results";
}
$conn->close();
$users = DB::table('users')->get();
foreach ($users as $user) {
echo $user->name;
}
$users = $db->query('SELECT * FROM users');
echo $twig->render('users.html', ['users' => $users]);
無論使用哪種方法,都應該注意對輸入進行適當的過濾和轉義,以防止SQL注入和其他安全漏洞。