mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assocRecupera una fila de resultados como un array asociativo

Advertencia

Esta extensión fue declarada obsoleta en PHP 5.5.0 y eliminada en PHP 7.0.0. En su lugar debería utilzarse las extensiones MySQLi o PDO_MySQL. Véase también la guía MySQL: elegir una API. Las alternativas a esta función son:

Descripción

mysql_fetch_assoc(resource $result): array

Devuelve un array asociativo que corresponde a la fila recuperada y mueve el puntero de datos interno hacia adelante. mysql_fetch_assoc() es equivalente a llamar a mysql_fetch_array() con MYSQL_ASSOC como segundo parámetro opcional. Únicamente devuelve un array asociativo.

Parámetros

result

El resultado resource que está siendo evaluado. Este resultado proviene de una llamada a mysql_query().

Valores devueltos

Devuelve un array asociativo de strings que corresponde a la fila recuperada, o false si no hay más filas disponibles.

Si dos o más columnas del resultado tienen los mismos nombres de campo, la última columna tomará precedencia. Para acceder a la/s otra/s columna/s con el mismo nombre, se tendrá que acceder al resultado con índices numéricos mediante el uso de mysql_fetch_row() o agregando sobrenombres. Véase el ejemplo en la descripción de mysql_fetch_array() respecto a los sobrenombres.

Ejemplos

Ejemplo #1 Un ejemplo desarrolado de mysql_fetch_assoc()

<?php

$conexión
= mysql_connect("localhost", "usuario_mysql", "contraseña_mysql");

if (!
$conexión) {
echo
"No pudo conectarse a la BD: " . mysql_error();
exit;
}

if (!
mysql_select_db("nombre_de_la_bd")) {
echo
"No ha sido posible seleccionar la BD: " . mysql_error();
exit;
}

$sql = "SELECT id as id_usuario, nombre_completo, estatus_usuario
FROM alguna_tabla
WHERE estatus_usuario = 1"
;

$resultado = mysql_query($sql);

if (!
$resultado) {
echo
"No se pudo ejecutar con exito la consulta ($sql) en la BD: " . mysql_error();
exit;
}

if (
mysql_num_rows($resultado) == 0) {
echo
"No se han encontrado filas, nada a imprimir, asi que voy a detenerme.";
exit;
}

// Mientras exista una fila de datos, colocar esa fila en $fila como un array asociativo
// Nota: Si solo espera una fila, no hay necesidad de usar un bucle
// Nota: Si coloca extract($fila); dentro del siguiente bucle,
// estará creando $id_usuario, $nombre_completo, y $estatus_usuario
while ($fila = mysql_fetch_assoc($resultado)) {
echo
$fila["id_usuario"];
echo
$fila["nombre_completo"];
echo
$fila["estatus_usuario"];
}

mysql_free_result($resultado);

?>

Notas

Nota: Rendimiento

Algo importante a observar es que el uso de mysql_fetch_assoc() no es significativamente más lento que el uso de mysql_fetch_row(), aunque provee un valor añadido considerable.

Nota: Los nombres de los campos devueltos por esta función son sensibles a mayúsculas y minúsculas.

Nota: Esta función define campos NULOS al valor null de PHP.

Ver también

add a note add a note

User Contributed Notes 15 notes

up
6
marREtijn dot posthMOuma at hoVEme dot nl
21 years ago
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>";
}
up
4
joe at kybert dot com
20 years ago
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!?
up
0
Typer85 at gmail dot com
17 years ago
Please be advised that the resource result that you pass to this function can be thought of as being passed by reference because a resource is simply a pointer to a memory location.

Because of this, you can not loop through a resource result twice in the same script before resetting the pointer back to the start position.

For example:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

   
// Display.

   
echo $queryContent[ 0 ];
}

// We looped through the resource result already so the
// the pointer is no longer pointing at any rows.

// If we decide to loop through the same resource result
// again, the function will always return false because it
// will assume there are no more rows.

// So the following code, if executed after the previous code
// segment will not work.

while( $queryContent = mysql_fetch_row( $queryResult ) {

   
// Display.

   
echo $queryContent[ 0 ];
}

// Because $queryContent is now equal to FALSE, the loop
// will not be entered.

?>
----------------

The only solution to this is to reset the pointer to make it point at the first row again before the second code segment, so now the complete code will look as follows:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

   
// Display.

   
echo $queryContent[ 0 ];
}

// Reset Our Pointer.

mysql_data_seek( $queryResult );

// Loop Again.

while( $queryContent = mysql_fetch_row( $queryResult ) {

   
// Display.

   
echo $queryContent[ 0 ];
}

?>
----------------

Of course you would have to do extra checks to make sure that the number of rows in the result is not 0 or else mysql_data_seek itself will return false and an error will be raised.

Also please note that this applies to all functions that fetch result sets, including mysql_fetch_row, mysql_fetch_assos, and mysql_fetch_array.
up
-4
george at georgefisher dot com
15 years ago
Thanks to to R. Bradley for the implode idea. The following fixes a few bugs and includes quote_smart functionality (and has been tested)

<?php
  
function mysql_insert_assoc ($my_table, $my_array) {
  
  
//
   // Insert values into a MySQL database
   // Includes quote_smart code to foil SQL Injection
   //
   // A call to this function of:
   //
   //  $val1 = "foobar";
   //  $val2 = 495;
   //  mysql_insert_assoc("tablename", array(col1=>$val1, col2=>$val2, col3=>"val3", col4=>720, col5=>834.987));
   //
   // Sends the following query:
   //  INSERT INTO 'tablename' (col1, col2, col3, col4, col5) values ('foobar', 495, 'val3', 720, 834.987)
   //

      
global $db_link;
      
      
// Find all the keys (column names) from the array $my_array
      
$columns = array_keys($my_array);

      
// Find all the values from the array $my_array
      
$values = array_values($my_array);
      
      
// quote_smart the values
      
$values_number = count($values);
       for (
$i = 0; $i < $values_number; $i++)
         {
        
$value = $values[$i];
         if (
get_magic_quotes_gpc()) { $value = stripslashes($value); }
         if (!
is_numeric($value))    { $value = "'" . mysql_real_escape_string($value, $db_link) . "'"; }
        
$values[$i] = $value;
         }
        
      
// Compose the query
      
$sql = "INSERT INTO $my_table ";

      
// create comma-separated string of column names, enclosed in parentheses
      
$sql .= "(" . implode(", ", $columns) . ")";
      
$sql .= " values ";

      
// create comma-separated string of values, enclosed in parentheses
      
$sql .= "(" . implode(", ", $values) . ")";
      
      
$result = @mysql_query ($sql) OR die ("<br />\n<span style=\"color:red\">Query: $sql UNsuccessful :</span> " . mysql_error() . "\n<br />");

       return (
$result) ? true : false;
   }
?>
up
-4
jono
18 years ago
Note that the field names quoted within $row[] are case sensitive whereas many sql commands are case insensitive.
up
-6
Daniel Chcouri - 333222 +A-T+ gmail
15 years ago
Fetching all the results to array with one liner:

<?php
$result
= mysql_query(...);
while((
$resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
?>
up
-5
benlanc at ster dot me dot uk
19 years ago
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);
?>
up
-4
R. Bradley
18 years ago
In response to Sergiu's function - implode() would make things a lot easier ... as below:

<?php
  
function mysql_insert_assoc ($my_table, $my_array) {

      
// Find all the keys (column names) from the array $my_array
      
$columns = array_keys($my_array);

      
// Find all the values from the array
      
$values = array_values($my_array);

      
// We compose the query
      
$sql = "insert into `$my_table` ";
      
// implode the column names, inserting "\", \"" between each (but not after the last one)
       // we add the enclosing quotes at the same time
      
$sql .= "(\"" . implode("\", \"", $column_names) . "\")";
      
$sql .= " values ";
      
// Same with the values
      
$sql .= "(" . implode(", ", $values) . ")";

      
$result = mysql_query($sql);

       if (
$result)
       {
           echo
"The row was added sucessfully";
           return
true;
       }
       else
       {
           echo (
"The row was not added<br>The error was" . mysql_error());
           return
false;
       }
   }
?>

Thus, a call to this function of:
mysql_insert_assoc("tablename", array("col1"=>"val1", "col2"=>"val2"));

Sends the following sql query to mysql:
INSERT INTO `tablename` ("col1", "col2") VALUES ("val1", "val2")
up
-5
jo at durchholz dot org
19 years ago
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.
up
-6
erik[at]phpcastle.com
19 years ago
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);
  }
?>
up
-7
chasfileDELETE_ALL_CAPS at gmail dot com
18 years ago
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 ))
up
-7
josh at joshstrike dot com
15 years ago
Here's a nifty function to copy a whole table to another table. Takes as its arguments
$z -> the result of a SQL query with columns matching the table you're copying into.
$toTable -> string name of the table to copy into.
$link_identifier -> the db resource of the table you're copying into.
If anyone can find a faster way to do this, I'd be glad to know about it...

<?php
function mysql_multirow_copy($z,$toTable,$link_identifier) {
   
$fields = "";
    for (
$i=0;$i<mysql_num_fields($z);$i++) {
        if (
$i>0) {
           
$fields .= ",";
        }
       
$fields .= mysql_field_name($z,$i);
    }
   
$q = "INSERT INTO $toTable ($fields) VALUES";
   
$c = 0;
   
mysql_data_seek($z,0); //critical reset in case $z has been parsed beforehand. !
   
while ($a = mysql_fetch_assoc($z)) {
        foreach (
$a as $as) {
           
$a[key($a)] = addslashes($as);
           
next ($a);
        }
        if (
$c>0) {
           
$q .= ",";
        }
       
$q .= "('".implode(array_values($a),"','")."')";
       
$c++;
    }
   
$q .= ";";
   
$z = mysql_query($q,$link_identifier);
    return (
$q);
}
?>
up
-10
nick at homefeedback dot com
17 years ago
function array2table: small fix to the post below that handles data returned from mysql that is either null or 0...

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 (
false !== ($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

?>
up
-8
moverton at northshropshiredc dot gov dot uk
20 years ago
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.
up
-13
bkfake-php at yahoo dot com
10 years ago
Although deprecated as of PHP 5.5, the mySQL function do NOT trigger an E_DEPRECATED error
To Top