0
$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_array = 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.

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

whats the difference between this one and the one from Pablo Santo Cruz
-1

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.

1 Comment

Holy moly that's ugly. You could avoid the entire business by simply writing your query properly (specifying fields with aliases instead of a *) and then $row will contain those field aliases as keys, which you stuff into another table. That whole code block would be reduced to about 6 lines.
-1
  $res = mysql_query($sql);
    $data = array();
    while(($row[] = mysql_fetch_array($res)) !== false) {
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.