简体   繁体   中英

How to index the result of a mySql query as an array of array?

If I need to select and use information of every element of a table in a database the procedure would be this:

$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());

Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:

$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....

But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).

As an example:

echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];

should print for every selected element of the table the value of field i.

Is there a function that will do the job for me? If not, any suggestions on how to do it?

Thanks in advance for help.

I don't think there is such a method; you have to do it yourself.

This may be an alternative

$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
    $arr[] = $row;
}
var_dump($arr);

Or

$res = mysql_query("..SQL...");
for
(
    $arr = array(); 
    $row = mysql_fetch_assoc($res); 
    $arr[] = $row
);
var_dump($arr);

try with something like:

$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
    $query_result_array[] = $row;
}

then you access your data like:

echo $query_result_array[0]['field_i'];

based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function

function sqlArr($sql) { return an array consists of 
  $ret = array();
  $res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
  if ($res) {
    while ($row = mysql_fetch_assoc($res)) {
      $ret[] = $row;
    }
  }
  return $ret;
}

$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
  echo $row['name'],$row['sex'];
}

this resulting array have different structure from what you asked, but it is way more convenient too. if you still need yours unusual one, you have to tell how you gonna use it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM