mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc --  Обрабатывает ряд результата запроса и возвращает ассоциативный массив.

Описание

array mysql_fetch_assoc ( resource result )

Возвращает ассоциативный массив с названиями индексов, соответсвующими названиям колонок или FALSE если рядов больше нет.

Функция mysql_fetch_assoc() аналогична вызову функции mysql_fetch_array() со вторым параметром, равным MYSQL_ASSOC. Функция возвращает только ассоциативный массив. Если вам нужны как ассоциативные, так и численные индексы в массиве, обратитесь к функции mysql_fetch_array().

Если несколько колонок в запросе имеют одинаковые имена, значение ключа массива с индексом названия колонок будет равно значению последней из колонок. Чтобы работать с первыми, используйте функции, возвращающие не ассоциативный массив: mysql_fetch_row(), либо используйте алиасы. Смотрите пример использования алиасов в SQL в описании функции mysql_fetch_array().

Важно заметить, что mysql_fetch_assoc() работает НЕ медленнее, чем mysql_fetch_row(), предоставляя более удобный доступ к данным.

Замечание: Имена полей, возвращаемые этой функцией, регистро-зависимы.

Пример 1. Расширенный пример использования mysql_fetch_assoc()

<?php

   $conn
= mysql_connect("localhost", "mysql_user", "mysql_password");
  
   if (!
$conn) {
       echo
"Unable to connect to DB: " . mysql_error();
       exit;
   }
  
   if (!
mysql_select_db("mydbname")) {
       echo
"Unable to select mydbname: " . mysql_error();
       exit;
   }
  
  
$sql = "SELECT id as userid, fullname, userstatus
           FROM  sometable
           WHERE  userstatus = 1"
;

  
$result = mysql_query($sql);

   if (!
$result) {
       echo
"Could not successfully run query ($sql) from DB: " . mysql_error();
       exit;
   }
  
   if (
mysql_num_rows($result) == 0) {
       echo
"No rows found, nothing to print so am exiting";
       exit;
   }

  
// До тех пор, пока в результате содержатся ряды, помещаем их в
   // ассоциативный массив.
   // Заметка: если запрос возвращает только один ряд -- нет нужды в цикле.
   // Заметка: если вы добавите extract($row); в начало цикла, вы сделаете
   //          доступными переменные $userid, $fullname, $userstatus.
  
while ($row = mysql_fetch_assoc($result)) {
       echo
$row["userid"];
       echo
$row["fullname"];
       echo
$row["userstatus"];
   }
      
  
mysql_free_result($result);

?>

См. также mysql_fetch_row(), mysql_fetch_array(), mysql_query() и mysql_error().



mysql_fetch_assoc
paintedgauthier at gmail dot com
04-Mar-2006 01:49
Sorry the last one i posted does a normal non-mysql array , this will work the magic on a assoc array

<? function assoc_array_to_mysql() {
global
$array;
  
$update = 'update player set ';
   foreach(
$array as $key => $value) {
       if (
$i) { $update .= key($array);
          
$check = current($array);
           if (isset(
$check)) {
          
$update .= '=\''.current($array).'\'';
           } else { 
$update .= '=null'; }
       } else {
$key = key($array);
      
$current = current($array);
      
$end = "where $key = $current"; }
  
      
next($array);
      
$check = key($array);
       if (isset(
$check)) {
           if (
$i) {$update .= ', '; }
       } else {
$update .= ' '.$end; }
    
$i++;
   }
  
$result = mysql_query($update) or die(mysql_oops($update));
   echo
'Updated';
 }
?>
chasfileDELETE_ALL_CAPS at gmail dot com
23-Feb-2006 11:26
What if you *want* a two dimensional array?  Useful for output as an HTML table, for instance.

function mysql_resultTo2DAssocArray ( $result) {
   $i=0;
   $ret = array();
   while ($row = mysql_fetch_assoc($result)) {
       foreach ($row as $key => $value) {
           $ret[$i][$key] = $value;
           }
       $i++;
       }
   return ($ret);
   }

print_r(mysql_resultTo2DAssocArray(mysql_query("SELECT * FROM something")));

Array ( [0] => Array ( [symbol] => ARNA
         [datetime] => 2006-02-17 16:00:00
         [price] => 16.83 )
     [1] => Array ( [symbol] => CALP
         [datetime] => 2006-02-17 16:00:00
         [price] => 6.54 )
     [2] => Array ( [symbol] => CROX
         [datetime] => 2006-02-17 16:00:00
         [price] => 27.4 ))
jono
01-Feb-2006 09:22
Note that the field names quoted within $row[] are case sensitive whereas many sql commands are case insensitive.
Maviee at gmx dot net
13-Jan-2006 02:38
I'll show you a small function which creates a normal array out of a mysql_fetch_assoc foreach loop.
First of all, I want to say, I have the philosphy that a function has exactly one return point. That's why I'm working with a return variable.

Now here is the code:

public function DBSelect($statement)
{
   $ident = mysql_query($statement);
   $result = true;

   if ($ident == false || mysql_num_rows($ident) == 0)
       $result = false;

   // only create the array when everything went fine
   if ($result != false)
   {
       unset($result);
       // workaround to avoid a 2-dimensional array
       foreach(mysql_fetch_assoc($ident) as $key => $value)
       {
           $result[$key] = $value;
       }
       mysql_free_result($ident);
   }
   return $result;
}
13-Dec-2005 03:25
The following code retrieves all rows but adds an empty array element to the end:
   while ($arr[] = mysql_fetch_assoc($result));
One way to remove it is to also execute the following:
   array_pop($arr);
08-Oct-2005 07:03
This is a useful script for displaying MySQL results in an HTML table.

<?

function array2table($arr,$width)
   {
  
$count = count($arr);
   if(
$count > 0){
      
reset($arr);
      
$num = count(current($arr));
       echo
"<table align=\"center\" border=\"1\"cellpadding=\"5\" cellspacing=\"0\" width=\"$width\">\n";
       echo
"<tr>\n";
       foreach(
current($arr) as $key => $value){
           echo
"<th>";
           echo
$key."&nbsp;";
           echo
"</th>\n";   
           }   
       echo
"</tr>\n";
       while (
$curr_row = current($arr)) {
           echo
"<tr>\n";
          
$col = 1;
           while (
$curr_field = current($curr_row)) {
               echo
"<td>";
               echo
$curr_field."&nbsp;";
               echo
"</td>\n";
              
next($curr_row);
              
$col++;
               }
           while(
$col <= $num){
               echo
"<td>&nbsp;</td>\n";
              
$col++;       
           }
           echo
"</tr>\n";
          
next($arr);
           }
       echo
"</table>\n";
       }
   }

?>

<?

// Add DB connection script here

$query = "SELECT * FROM mytable";
$result = mysql_query($query);
while(
$row = mysql_fetch_assoc($result)){
 
$array[] = $row; }
      
array2table($array,600); // Will output a table of 600px width

?>
benlanc at ster dot me dot uk
23-Aug-2005 04:25
It probably without saying, but using list() in conjunction with mysql_fetch_assoc() does not work - use mysql_fetch_row() instead.

<?php
$sql
= "SELECT `id`,`field`,`value` FROM `table`";
$result = mysql_query($sql);

// this results in empty values for rowID,fieldName,myValue
list($rowID,$fieldName,$myValue) = mysql_fetch_assoc($result);

// this is what you want:
list($rowID,$fieldName,$myValue) = mysql_fetch_row($result);
?>
jo at durchholz dot org
21-Jun-2005 01:58
To sum up moverton at northshropshiredc dot gov dot uk and Olivier Fabre:

If the query is "SELECT something1, something2, .... FROM tbl WHERE some_condition", the keys in the returned array will be 'something1', 'something2', etc. *even for those "somethings" that are not just field names*.

Examples of non-fieldname "somethings" are:
NULL
NOW
MAX(some_fieldname)

I haven't tested whether this applies to table.fieldname, but I see no reason why it shouldn't (I'd suspect a typo in my code if I didn't get the expected results; I certainly have had my share of them!)

I found it most convenient to check for typos by simply var_dumping the resulting row, like this:

<?php
echo '<pre>Got this row:'
var_dump ($row);
echo
'</pre>';
?>

where $row is the result from the last call to mysql_fetch_assoc.
erik[at]phpcastle.com
14-May-2005 12:50
When you have to loop multiple times through the result of a query you can set the result pointer to 0 (zero) with mysql_data_seek ()

The advantage is that you do not have to query database twice with te same query :)

So:
<?php
  $query
= "
   SELECT *
   FROM database
  "
;

 
//Query database
 
$result = mysql_query ($query);

 
//Iterate result
 
while ($record = mysql_fetch_assoc ($result)){
  
print_r ($record);
  }

  ...

 
//Point to 0 (zero)
 
mysql_data_seek ($result, 0);

 
//Re-use the result
 
while ($record = mysql_fetch_assoc ($result)){
  
print_r ($record);
  }
?>
joe at kybert dot com
29-Sep-2004 01:07
Worth pointing out that the internal row pointer is incremented once the data is collected for the current row.

This means that multiple calls will iterate through the row data, so you DONT need to mysql_data_seek(..) between calls.

This is noted in the  mysql_fetch_row() docs, but not here!?
moverton at northshropshiredc dot gov dot uk
17-Sep-2004 05:27
Actually, Olivier, you're completely wrong about that, because there's a bug in your sample code. It will indeed return $row['MAX(time)'] - you have to pass the MySQL resource to mysql_fetch_assoc() and you're not doing that. This:

$row = mysql_fetch_assoc($conn)

...where $conn is your DB connection, would in fact produce a result. The complete example below is taken from my own self-written content management system:

$query = 'SELECT MAX(ctRevDate) FROM content group by ctPage';
$querySet = mysql_query($query, $conn);
$row = mysql_fetch_assoc($querySet);
print_r($row);

This produces:

Array
(
   [MAX(ctRevDate)] => 2004-01-15
)

..on my testbed. So it doesn't in fact need an alias at all.
marREtijn dot posthMOuma at hoVEme dot nl
04-Sep-2003 04:57
It appears that you can't have table.field names in the resulting array.
Just use an alias if your results come up empty and you are using multi-table query's:

$res=mysql_query("SELECT user.ID AS uID, order.ID AS oID FROM user, order WHERE ( order.userid=uID )";
while ($row=mysql_fetch_assoc($res)) {
   echo "<p>userid: $row['uID'], orderid: $row['oID']</p>";
}

<mysql_fetch_arraymysql_fetch_field>
 Last updated: Tue, 15 Nov 2005