Arevshatyan Gegham Arevshatyan Gegham - 5 months ago 9
MySQL Question

I want to get all of my database items

I've included this

PHP
file in my
index.php
, but I only get the first item from the database. How can I get all items from my database?

<?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"]?>

Answer

As you said you want all records from the database, so you need to use while loop like below:-

<?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
?>
Comments