Putting MYSQL results into a PHP Array [closed]
I have an array, using this structure.
$data = array(
array("firstnam开发者_开发问答e" => "Mary", "lastname" => "Johnson", "age" => 25),
array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18)
);
I want to read data from a MYSQL table into this array. Here is my code
$sql = "select * from mynames limit 10";
$result = mysql_query($sql);
$data = mysql_fetch_array($result, MYSQL_NUM);
The array is not filling up. Can anybody show me how to fill the array?
while($data = mysql_fetch_assoc($result)){
$row[] = $data;
}
print_r($row);
Are you looking to append results to $data
? If so, you can do something like this:
$data = array(
array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18)
);
$sql = "SELECT * FROM mynames LIMIT 10";
$result = mysql_query($sql);
while (($row = mysql_fetch_array($result, MYSQL_NUM)) !== false) {
$data[] = $row;
}
Or, if you're looking to merge the rows you get back from MySQL with the rows in $data
, you can do something like:
$i = 0;
while (($row = mysql_fetch_array($result, MYSQL_NUM)) !== false) {
$data[$i] = array_merge($data[$i], $row);
$i++;
}
mysql_fetch_array
will get the next row from the results, returning false
when there are no more rows. To propagate an array with all the results you need to iterate (e.g. with a while ($row = mysql_fetch_array(...
).
精彩评论