0

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"]?>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Arevshatyan Gegham
  • 121
  • 1
  • 2
  • 5

2 Answers2

1

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
?>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
1

This is because you need to loop your results that are in $page array. Try this:

<?php foreach($page as $value): ?>
    <h2><?=$value["name"]?></h2>
    <?=$value["price"]?>
<?php endforeach; ?>

if you need more info about foreach method go here

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Sebastian S
  • 807
  • 6
  • 15