我已在PHP
中包含此index.php
文件,但我只从数据库中获取第一项。如何从数据库中获取所有项目?
<?php
$sql = "SELECT name,price FROM items ORDER BY `id`";
$res = mysqli_query($conn, $sql);
$page = mysqli_fetch_assoc($res);
mysqli_close($conn);
?>
<h2><?=$page["name"]?></h2>
<?=$page["price"]?>
答案 0 :(得分:1)
正如您所说,您需要all records from the database
,因此您需要使用while loop
,如下所示: -
<?php
$sql = "SELECT name,price FROM items ORDER BY `id`"; // query
$res = mysqli_query($conn, $sql); // execute query
while($page = mysqli_fetch_assoc($res)){ // loop
echo "<h2>". $page["name"]."</h2>".$page["price"]; // print all record (You can change pattern of printing according to your wish )
}
mysqli_close($conn); // close connection
?>
答案 1 :(得分:1)
这是因为您需要循环$page
数组中的结果。试试这个:
<?php foreach($page as $value): ?>
<h2><?=$value["name"]?></h2>
<?=$value["price"]?>
<?php endforeach; ?>
如果您需要有关foreach方法的更多信息,请转到here