Ashok
Ashok

Reputation: 159

How to use array inside while loop so it can track every id fetching from database?

I'm fetching multiple rows from a database. That's why I use a while loop but I need every individual ID inside the while loop. How can I use an array inside the while loop? The friendid just prints the last result from the loop.I don't want to print the result inside the loop.

  while ($row = mysqli_fetch_assoc($run_sql))
   {
     $name = $row['name'];
     $friendid = $row['id'];  
   }
    echo $friendid;

Upvotes: 0

Views: 72

Answers (2)

Gulmuhammad Akbari
Gulmuhammad Akbari

Reputation: 2036

Try this

$ids = array();
  while ($row = mysqli_fetch_assoc($run_sql))
   {
     $name = $row['name'];
     $ids[] = $row['id'];  
   }
   print_r($ids);

Upvotes: 1

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

Create an empty array before the while loop. In each iteration of the loop, append the fetched row to this array.

$resultArr = array();
while ($row = mysqli_fetch_assoc($run_sql)){
    $resultArr[] = array($row['id'], $row['name']);
}
// display $resultArr array
var_dump($resultArr);

Upvotes: 0

Related Questions