Ctc Ctc - 5 months ago 17
SQL Question

Storing MySQL query result into a PHP array

Looking at all the questions are using the depreciated

mysql_fetch_assoc/array,
hence I don't think that this is a duplicate question.

I have a MySQL table with 5 columns,

ID | NAME | AGE | GENDER | HEIGHT


If I want to store the values of
NAME, AGE, GENDER
in a PHP array,

$query=$mysqli->query("SELECT NAME,AGE,GENDER FROM TableName")
while($result = $query->fetch_assoc()
{
$array = [];
}


Will my array be stored in the format of
$array=[[Name,Age,Gender],[Name,Age,Gender]]
?

If not, what would be my approach in doing this?

Answer

It's very simple. You just have to append the result variable in to main array. Like this,

$array =array();
while($result = $query->fetch_assoc()
{
$array[] = $result;
}

$result is an array (fetch_assoc it returns result-set in array) so just append that into main array to get the desired result.
($array=[[Name,Age,Gender],[Name,Age,Gender]])