mysql_fetch_array

(PHP 3, PHP 4, PHP 5)

mysql_fetch_array --  从结果集中取得一行作为关联数组,或数字数组,或二者兼有

说明

array mysql_fetch_array ( resource result [, int result_type] )

返回根据从结果集取得的行生成的数组,如果没有更多行则返回 FALSE

mysql_fetch_array()mysql_fetch_row() 的扩展版本。除了将数据以数字索引方式储存在数组中之外,还可以将数据作为关联索引储存,用字段名作为键名。

如果结果中的两个或以上的列具有相同字段名,最后一列将优先。要访问同名的其它列,必须用该列的数字索引或给该列起个别名。对有别名的列,不能再用原来的列名访问其内容(本例中的 'field')。

例子 1. 相同字段名的查询

select table1.field as foo, table2.field as bar from table1, table2

有一点很重要必须指出,用 mysql_fetch_array()不明显 比用 mysql_fetch_row() 慢,而且还提供了明显更多的值。

mysql_fetch_array() 中可选的第二个参数 result_type 是一个常量,可以接受以下值:MYSQL_ASSOC,MYSQL_NUM 和 MYSQL_BOTH。本特性是 PHP 3.0.7 起新加的。本参数的默认值是 MYSQL_BOTH。

如果用了 MYSQL_BOTH,将得到一个同时包含关联和数字索引的数组。用 MYSQL_ASSOC 只得到关联索引(如同 mysql_fetch_assoc() 那样),用 MYSQL_NUM 只得到数字索引(如同 mysql_fetch_row() 那样)。

注: 本函数返回的字段名是区分大小写的。

例子 2. mysql_fetch_array 使用 MYSQL_NUM

<?php
    mysql_connect
("localhost", "mysql_user", "mysql_password") or
        die(
"Could not connect: " . mysql_error());
    
mysql_select_db("mydb");

    
$result = mysql_query("SELECT id, name FROM mytable");

    while (
$row = mysql_fetch_array($result, MYSQL_NUM)) {
        
printf ("ID: %s  Name: %s", $row[0], $row[1]);
    }

    
mysql_free_result($result);
?>

例子 3. mysql_fetch_array 使用 MYSQL_ASSOC

<?php
    mysql_connect
("localhost", "mysql_user", "mysql_password") or
        die(
"Could not connect: " . mysql_error());
    
mysql_select_db("mydb");

    
$result = mysql_query("SELECT id, name FROM mytable");

    while (
$row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        
printf ("ID: %s  Name: %s", $row["id"], $row["name"]);
    }

    
mysql_free_result($result);
?>

例子 4. mysql_fetch_array 使用 MYSQL_BOTH

<?php
    mysql_connect
("localhost", "mysql_user", "mysql_password") or
        die(
"Could not connect: " . mysql_error());
    
mysql_select_db("mydb");

    
$result = mysql_query("SELECT id, name FROM mytable");

    while (
$row = mysql_fetch_array($result, MYSQL_BOTH)) {
        
printf ("ID: %s  Name: %s", $row[0], $row["name"]);
    }

    
mysql_free_result($result);
?>

参见 mysql_fetch_row()mysql_fetch_assoc()


add a note add a note User Contributed Notes
06-Jun-2006 05:14
Note that as unlikely as it might be, queries like the following will mess up an array that is of result_type MYSQL_BOTH:

SELECT 'hello', 'world' AS '0';
hdixonish at deltabravo dot com
18-May-2006 06:39
Just a fairly useful (to me at least!) "implementation" of mysql_fetch_assoc to stop the clobbering of identical column names and allow you to work out which table produced which result column when using a JOIN (or simple multiple-table) SQL query:
(assuming a live connection ...)
<?php
$sql
= "SELECT a.*, b.* from table1 a, table2 b WHERE a.id=b.id"; // example sql
$r = mysql_query($sql,$conn);
if (!
$r) die(mysql_error());
$numfields = mysql_num_fields($r);
$tfields = Array();
for (
$i=0;$i<$numfields;$i++)
{
  
$field mysql_fetch_field($r,$i);
  
$tfields[$i] = $field->table.'.'.$field->name;
}
while (
$row = mysql_fetch_row($r))
{
  
$rowAssoc = Array();
   for (
$i=0;$i<$numfields;$i++)
   {
      
$rowAssoc[$tfields[$i]] = $row[$i];
   }
//    do stuff with $rowAssoc as if it was $rowAssoc = mysql_fetch_assoc($r) you had used, but with table. prefixes
}
?>
let's you refer to $rowAssoc['a.fieldname'] for example.

[for real email addr, remove the ish]
tilmauder at yahoo dot com
16-Feb-2006 05:18
Remember that using a while() loop for traversing your result array is significantly slower than using a foreach() loop. Read the comments in the control structures section of this site for further details.
john at skem9 dot com
21-Jan-2006 08:13
my main purpose was to show the fetched array into a table, showing the results side by side instead of underneath each other, and heres what I've come up with.

just change the $display number to however many columns you would like to have, just dont change the $cols number or you might run into some problems.

<?php
$display
= 4;
$cols = 0;
echo
"<table>";
while(
$fetched = mysql_fetch_array($result)){
   if(
$cols == 0){
       echo
"<tr>\n";
   }
  
// put what you would like to display within each cell here
  
echo "<td>".$fetched['id']."<br />".$fetched['name']."</td>\n";
  
$cols++;
   if(
$cols == $display){
       echo
"</tr>\n";
      
$cols = 0;
   }
}
// added the following so it would display the correct html
if($cols != $display && $cols != 0){
  
$neededtds = $display - $cols;
   for(
$i=0;$i<$neededtds;$i++){
       echo
"<td></td>\n";
   }
     echo
"</tr></table>";
   } else {
   echo
"</table>";
}
?>

Hopefully this will save some of you a lot of searching.

any kind of improvements on this would be awesome!
andrea at 3site dot it
28-Dec-2005 11:51
alternative mysql_fetch_all

// array mysql_fetch_all(query:resource [, kind:string (default:'assoc' | 'row')])
function mysql_fetch_all($query, $kind = 'assoc') {
   $result = array();
   $kind = $kind === 'assoc' ? $kind : 'row';
   eval('while(@$r = mysql_fetch_'.$kind.'($query)) array_push($result, $r);');
   return $result;
}

// Example
$query = mysql_query($myquery) or die(mysql_error());
$result = mysql_fetch_all($query);
echo '<pre>'.print_r($result, true).'</pre>';
info at modulotech dot ch
23-Nov-2005 06:37
I think using a for loop to display fetched rows from a table is more convenient than a while loop, since one have directely access to the record number:

$reclist = mysql_query("SELECT field FROM table",$db)
               or die(mysql_errno()." : ".mysql_error());

for ($j=0; $rec=mysql_fetch_array($reclist); $j++){
     printf("%s - %s<br>\n",$j,$rec["field"]);   
}

Hope this is usefull. Ali
tim at wiltshirewebs dot com
14-Nov-2005 09:49
Here's a quick way to duplicate or clone a record to the same table using only 4 lines of code:

// first, get the highest id number, so we can calc the new id number for the dupe
// second, get the original entity
// third, increment the dupe record id to 1 over the max
// finally insert the new record - voila - 4 lines!

$id_max = mysql_result(mysql_query("SELECT MAX(id) FROM table_name"),0,0) or die("Could not execute query");
$entity = mysql_fetch_array(mysql_query("SELECT * FROM table." WHERE id='$id_original'),MYSQL_ASSOC) or die("Could not select original record"); // MYSQL_ASSOC forces a purely associative array and blocks twin key dupes, vitally, it brings the keys out so they can be used in line 4
$entity["id"]=$id_max+1;
mysql_query("INSERT INTO it_pages (".implode(", ",array_keys($Entity)).") VALUES ('".implode("', '",array_values($Entity))."')");

Really struggled in cracking this nut - maybe there's an easier way out there?  Thanks to other posters for providing inspiration. Good luck - Tim
eddie at nailchipper dot com
04-Nov-2005 02:58
mob AT stag DOT ru has a nice function for getting simple arrays from MySQL but it has a serious bug. The MySQL link being set as an argument is NULL when no link is supplied meaning that you're passing NULL to the mysql funcctions as a link, which is wrong. I am not using multitple connections so I removed the link and using the global link. If you want to support multiple links check to see if its set first.

/*
* to support multiple links add the $link argument to function then
* test it before you use the link
*
* if(isset($link))
*  if($err=mysql_errno($link))return $err;
* else
*  if($err=mysql_errno())return $err;
*/

function mysql_fetch_all($query){
 $r=@mysql_query($query);
 if($err=mysql_errno())return $err;
 if(@mysql_num_rows($r))
  while($row=mysql_fetch_array($r))$result[]=$row;
 return $result;
}
function mysql_fetch_one($query){
 $r=@mysql_query($query);
 if($err=mysql_errno())return $err;
 if(@mysql_num_rows($r))
 return mysql_fetch_array($r);
}
kunky at mail dot berlios dot de
01-Oct-2005 06:41
This is very useful when the following query is used:

`SHOW TABLE STATUS`

Different versions of MySQL give different responses to this.

Therefore, it is better to use mysql_fetch_array() because the numeric references given my mysql_fetch_row() give very different results.
joelwan at gmail dot com
06-Sep-2005 06:14
Try Php Object Generator: http://www.phpobjectgenerator.com

It's kind of similar to Daogen, which was suggested in one of the comments above, but simpler and easier to use.

Php Object Generator generates the Php Classes for your Php Objects. It also provides the database class so you can focus on more important aspects of your project. Hope this helps.
yashiro at esfera dot cl
30-Jun-2005 09:36
This is a simple function that outputs a String with a table with the name of fields and their respective values, pretty useful
u insert a result like this : $result = mysql_query("select * from table", $db)

   /*Esta funcion genera automaticamente una tabla que muestra el resultado de un mysql_query,
   basta con invocar la funcion y con echo imprimirla*/
   function muestra_select($result){
       $tabla = "\n\t".'<table border="2" align="center" cellpadding="2" cellspacing="2">'."\n";
       for($i = 0; $i < mysql_num_fields($result); $i++){
           $aux = mysql_field_name($result, $i);
           $tabla .= "\t\t<th>".$aux."</th>\n";
       }
       while ($linea = mysql_fetch_array($result, MYSQL_ASSOC)) {
           $tabla .= "\t\t<tr>\n";
           foreach ($linea as $valor_col) {
               $tabla .= "\t\t\t".'<td>'.$valor_col.'</td>'."\n";
           }
           $tabla .= "\t\t</tr>\n";
       }
       $tabla .= "\t</table>\n";
       return $tabla;
   }
romans at servidor dot unam dot mx
13-May-2005 01:31
Regarding duplicated field names in queries, I wanted some way to retrieve rows without having to use alias, so I wrote this class that returns rows as 2d-arrays

<?
  $field
= $drow['table']['column'];
?>

Here is the code:

<?
 
class mysql_resultset
 
{
   var
$results, $map;

   function
mysql_resultset($results)
   {
    
$this->results = $results;
    
$this->map = array();

    
$index = 0;
     while (
$column = mysql_fetch_field($results))
     {
      
$this->map[$index++] = array($column->table, $column->name);
     }
   }

   function
fetch()
   {
     if (
$row = mysql_fetch_row($this->results))
     {
      
$drow = array();

       foreach (
$row as $index => $field)
       {
         list(
$table, $column) = $this->map[$index];
        
$drow[$table][$column] = $row[$index];
       }

       return
$drow;
     }
     else
       return
false;
   }
  }
?>

The class is initialized with a mysql_query result:

<?
  $resultset
= new mysql_resultset(mysql_query($sql));
?>

The constructor builds an array that maps each field index to a ($table, $column) array so we can use mysql_fetch_row and access field values by index in the fetch() method. This method then uses the map to build up the 2d-array.

An example:

<?
  $sql
=
  
"select orders.*, clients.*, productos.* ".
  
"from orders, clients, products ".
  
"where join conditions";

 
$resultset = new mysql_resultset(mysql_query($sql));

  while (
$drow = $resultset->fetch())
  {
   echo
'No.: '.$drow['orders']['number'].'<br>';
   echo
'Client: '.$drow['clients']['name'].'<br>';
   echo
'Product: '.$drow['products']['name'].'<br>';
  }
?>

I hope others find this useful as it has been to me.
mob AT stag DOT ru
24-Jan-2005 03:16
I wrote some utility functions to improve usability and readability, and use them everywhere in my code. I suppose they can help.

function mysql_fetch_all($query,$MySQL=NULL){
 $r=@mysql_query($query,$MySQL);
 if($err=mysql_errno($MySQL))return $err;
 if(@mysql_num_rows($r))
  while($row=mysql_fetch_array($r))$result[]=$row;
 return $result;
}
function mysql_fetch_one($query,$MySQL=NULL){
 $r=@mysql_query($query,$MySQL);
 if($err=mysql_errno($MySQL))return $err;
 if(@mysql_num_rows($r))
 return mysql_fetch_array($r);
}

Example use:
if(is_array($rows=mysql_fetch_all("select * from sometable",$MySQL))){
 //do something
}else{
 if(!is_null($rows)) die("Query failed!");
}
joey at clean dot q7 dot com
19-Apr-2004 10:47
The issue of NULL fields seems to not be an issue anymore (as of 4.2.2 at least).  mysql_fetch_* now seems to fully populate the array and put in entries with values of NULL when that is what the database returned.  This is certainly the behaviour I expected, so I was concerned when i saw the notes here, but testing shows it does work the way I expected.
Ben
07-Apr-2004 02:59
One of the most common mistakes that people make with this function, when using it multiple times in one script, is that they forget to use the mysql_data_seek() function to reset the internal data pointer.

When iterating through an array of MySQL results, e.g.

<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
   foreach (
$line as $col_value) {
       echo
$col_value . '<br />';
   }
}
?>

the internal data pointer for the array is advanced, incrementally, until there are no more elements left in the array. So, basically, if you copy/pasted the above code into a script TWICE, the second copy would not create any output. The reason is because the data pointer has been advanced to the end of the $line array and returned FALSE upon doing so.

If, for some reason, you wanted to interate through the array a second time, perhaps grabbing a different piece of data from the same result set, you would have to make sure you call

<?php
mysql_data_seek
($result, 0);
?>

This function resets the pointer and you can re-iterate through the $line array, again!
sigit at djpkpd dot go dot id, harris at djpkpd dot go dot id
25-Mar-2003 02:28
if you have to use the field name with number like 1,2,..etc, it cause a problem when you fetch it with mysql_fetch_array.
An index array will contain a field name.
The solusion is:
1. Use mysql_fetch_assoc to escape the result to html;
2. Use alias and choose another name of field in mysql_query
hanskrentel at yahoo dot de
09-Jan-2003 05:25
for the problem with fields containing null values in an associated array, feel free to use this function. i've got no more problems with it, just drop it in your script:

/*
*    mysql_fetch_array_nullsafe
*
*
*    get a result row as an enumerated and associated array
*    ! nullsafe !
*
*    parameter:    $result
*                    $result:    valid db result id
*
*    returns:    array | false (mysql:if there are any more rows)
*
*/
function mysql_fetch_array_nullsafe($result) {
   $ret=array();

   $num = mysql_num_fields($result);
   if ($num==0) return $ret;

   $fval = mysql_fetch_row ($result);
     if ($fval === false) return false;

   $i=0;
     while($i<$num)
       {
           $fname[$i] = mysql_field_name($result,$i);           
           $ret[$i] = $fval[$i];            // enum
           $ret[''.$fname[$i].''] = $fval[$i];    // assoc
           $i++;
       }

   return $ret;
}
juancri at tagnet dot org
12-Nov-2002 05:41
An example with mysql_fetch_array():

   $result = mysql_query("SELECT name FROM table WHERE id=8");
   $array = mysql_fetch_array($result);

$array will be:

   array ([0] => "John", ['name'] => "John")

Then you can access to the results:

   echo "The name is " . $array[0];
   // or
   echo "The name is " . $array['name'];

But the array is not referential. $array[0] is not a reference to $array['name'] or $array['name'] to $array[0], they are not relationed between. Because of that, the system will use excesive memory. With large columns, try to use mysql_fetch_assoc() or mysql_fetch_row() only.
dkantha at yahoo dot com
11-Nov-2002 08:27
I did find 'jb at stormvision's' code useful above, but instead of the number of rows you need the number of fields; otherwise you get an error.

So, it should read like the following:

$result=mysql_query("select * from mydata order by 'id'")or die('died');
$num_fields = mysql_num_fields($result);
$j=0;
$x=1;
while($row=mysql_fetch_array($result)){ 
  for($j=0;$j<$num_fields;$j++){
   $name = mysql_field_name($result, $j);
   $object[$x][$name]=$row[$name];
  }$x++;
}

For Later in the script you may use the below array to gain access to your data

$i=1;
$ii=count($object);        //quick access function
for($i=1;$i<=$ii;$i++){
echo $object[$i]['your_field_name'];
}

I have tested this in my apps and it works great! :-)
glenn dot hoeppner at yakhair dot com
10-Oct-2002 05:04
Just another workaround for columns with duplicate names...

Modify your SQL to use the AS keyword.

Instead of:
$sql = "SELECT t1.cA, t2.cA FROM t1, t2 WHERE t1.cA = t2.cA";
 
Try:
$sql = "SELECT t1.cA AS foo1, t2.cA AS foo2 FROM t1, t2 WHERE t1.cA = t2.cA";

Then you can reference the results by name in the array:
  $row[foo1], $row[foo2]
tslukka at cc dot hut dot fi
26-Sep-2002 05:20
If you think MySQL (or other) database
handling is difficult and requires lot's of
code, I recommend that you try http://titaniclinux.net/daogen/

DaoGen is a program source code generator
that supports PHP and Java. It makes database
programming quick and easy. Generated sources
are released under GPL.
robjohnson at black-hole dot com
15-Jun-2002 06:22
Benchmark on a table with 38567 rows:

mysql_fetch_array
MYSQL_BOTH: 6.01940000057 secs
MYSQL_NUM: 3.22173595428 secs
MYSQL_ASSOC: 3.92950594425 secs

mysql_fetch_row: 2.35096800327 secs
mysql_fetch_assoc: 2.92349803448 secs

As you can see, it's twice as effecient to fetch either an array or a hash, rather than getting both.  it's even faster to use fetch_row rather than passing fetch_array MYSQL_NUM, or fetch_assoc rather than fetch_array MYSQL_ASSOC.  Don't fetch BOTH unless you really need them, and most of the time you don't.
barbieri at NOSPAMzero dot it
31-May-2002 09:21
Here is a suggestion to workaround the problem of NULL values:

// get associative array, with NULL values set
$record = mysql_fetch_array($queryID,MYSQL_ASSOC);

// set number indices
if(is_array($record))
{
   $i = 0;
   foreach($record as $element)
       $record[$i++] = $element;
}

This way you can access $result array as usual, having NULL fields set.
mjm at porter dot appstate dot edu
13-Mar-2002 11:48
If you perform a SELECT query which returns different columns with duplicate names, like this:

--------
$sql_statement = "SELECT tbl1.colA, tbl2.colA FROM tbl1 LEFT JOIN tbl2 ON tbl1.colC = tbl2.colC";

$result = mysql_query($sql_statement, $handle);

$row = mysql_fetch_array($result);
--------

Then

$row[0] is equivalent to $row["colA"]

but

$row[1] is not equivalent to $row["colA"].

Moral of the story: You must use the numerical index on the result row arrays if column names are not unique, even if they come from different tables within a JOIN. This would render mysql_fetch_assoc() useless.

[Ed. note - or you could do the usual 'select tbl1.colA as somename, tbl2.colA as someothername. . .' which would obviate the problem. -- Torben]
techquest at onebox dot com
21-Jan-2002 09:19
Hi to enumerate a result set with out worrying about null values just use below code.

 while($myrow = mysql_fetch_row($result))
 {
 print " <tr> ";
  for($x=0; $x <= count($myrow); $x++)
  {
   print "<td>myrow[$x]</td>";
  }
 print "</tr>";
}

[ed note: tidied code so it actually works]
some at gamepoint dot net
11-Jan-2002 03:13
I never had so much trouble with null fields but it's to my understanding that extract only works as expected when using an associative array only, which is the case with mysql_fetch_assoc() as used in the previous note.

However a mysql_fetch_array will return field values with both the numerical and associative keys, the numerical ones being those extract() can't handle very well.
You can prevent that by calling mysql_fetch_array($result,MYSQL_ASSOC) which will return the same result as mysql_fetch_assoc and is extract() friendly.