将MySQL查询结果存储到PHP数组中[重复]
问题描述:
This question already has an answer here:
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?
</div>
答
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]]
)
答
$data =[];
$i=0;
while($result = $query->fetch_assoc(){
$data[$i][] = $result;
$i++;
}