开发者

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 functi开发者_Go百科on 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.


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);


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


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜