在PHP中,顯示數(shù)據(jù)庫內容的方法有以下幾種:
mysqli
或PDO
擴展來連接到數(shù)據(jù)庫、執(zhí)行查詢語句并獲取結果集,并使用循環(huán)遍歷結果集中的數(shù)據(jù)。$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]);
無論使用哪種方法,都應該注意對輸入進行適當?shù)倪^濾和轉義,以防止SQL注入和其他安全漏洞。