开发者

Mysql query mysql_fetch_array

开发者 https://www.devze.com 2023-02-09 13:48 出处:网络
$data = mysql_query(\"SELECT * FROM users); now the data is stored in the $data variable. I would like to store the mysql data in an array and return that.
$data = mysql_query("SELECT * FROM users);

now the data is stored in the $data variable. I would like to store the mysql data in an array and return that.

$data_arra开发者_Python百科y = mysql_fetch_assoc($data);

This would store the first row (the first array) of the data.

now to store all the rows I was wondering what should I do.


The standard approach:

    $res = mysql_query($sql);
    $data = array();
    while(($row = mysql_fetch_array($res)) !== false) {
       $data[] = $row;
    }

// now $data is an array with all rows

http://php.net/manual/en/function.mysql-fetch-array.php

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

This approach works with mysql_fetch_* functions.


while ($row = mysql_fetch_assoc($data))
   {
     array_push($data_array,$row);
   }


If your result set is big, it's not a good idea to do that. It could use a lot of memory on the process.

Having said that, you could store the whole thing on an array like this:

<?php

$query="select * from table_xyz";
$result = mysql_query($query) or die(mysql_error());
$arr_table_result=mysql_fetch_full_result_array($result);

function mysql_fetch_full_result_array($result)
{
    $table_result=array();
    $r=0;
    while($row = mysql_fetch_assoc($result)){
        $arr_row=array();
        $c=0;
        while ($c < mysql_num_fields($result)) {        
            $col = mysql_fetch_field($result, $c);    
            $arr_row[$col -> name] = $row[$col -> name];            
            $c++;
        }    
        $table_result[$r] = $arr_row;
        $r++;
    }    
    return $table_result;
}

?>

Got the code sample from the PHP site.


  $res = mysql_query($sql);
    $data = array();
    while(($row[] = mysql_fetch_array($res)) !== false) {
    }
0

精彩评论

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