在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注入和其他安全漏洞。