开发者

Putting MYSQL results into a PHP Array [closed]

开发者 https://www.devze.com 2023-04-05 15:34 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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(...).

0

精彩评论

暂无评论...
验证码 换一张
取 消