Ridwanul Hafiz Ridwanul Hafiz - 7 months ago 14
SQL Question

while loop inside an array

$query = mysql_query("SELECT * FROM tableName WHERE status='confirm' ORDER BY datetime DESC ");
$invoice = mysql_fetch_assoc($query);


How do I echo mysql fetch data like as following:

$data = array(
array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18),
array("firstname" => "James", "lastname" => "Brown", "age" => 31),
array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7),
array("firstname" => "Michael", "lastname" => "Davis", "age" => 43),
array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24),
array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27)
);

Answer

You need to iterate through the results and add the values to your data array:

$query = mysql_query("SELECT * FROM tableName WHERE status='confirm' ORDER BY datetime DESC ");
$data = array();
while ($invoice = mysql_fetch_assoc($query)) {
  $data[] = array(
    'firstname' => $invoice['firstname'],
    'lastname' => $invoice['lastname'],
    'age' => $invoice['age'],
  );
}

mysql_fetch_assoc($query) returns only one row, so as long as it returns a result row (while), the loop is running and adds the values to the $data array.