-1

I have problem display database use if and while in code me.

Where I have 4 data in database.

I want display all data with using if, but it only displays 1 data.

if($Z = mysqli_fetch_assoc($Y)){
  <!-- Data all display -->
} else {

}

and me using data with while, data all display

while($Z = mysqli_fetch_assoc($Y)){
    <!-- Data all display -->
}

How to display all data using if?

Milo
  • 3,197
  • 9
  • 27
  • 40
wiihii
  • 37
  • 6

2 Answers2

0

It's not possible. Every time you call mysqli_fetch_assoc() on your $Y variable (which is a resource), you fetch the next row.

You have to always fetch in a loop (while or for) with mysqli_fetch_assoc().

If you want to fetch all results at once, you must use mysqli_fetch_all().

Edit: While not directly possible using mysqli_fetch_assoc() you can also do something like this:

<?php

$results = [];
while($Z = mysqli_fetch_assoc($Y)) {
  $results[] = $Z;
}

Then all your rows will be stored in $results.

Rikudou_Sennin
  • 1,202
  • 10
  • 24
0

If i am not wrong you used IF statement just for check that is there any row fetched are not.There is one way to do this check below code.

First check if any row fetched with if statement and then use while to display all data.

 $rowcount=mysqli_num_rows($Y);

    if($rowcount>0){

    while($Z = mysqli_fetch_assoc($Y)){
        <!-- Data all display -->
    }  
  }else{
   echo "no data found";
}
CodeBreaker
  • 389
  • 2
  • 9