PHP Conference Nagoya 2025

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assocLit une ligne de résultat MySQL dans un tableau associatif

Avertissement

Cette extension était obsolète en PHP 5.5.0, et a été supprimée en PHP 7.0.0. À la place, vous pouvez utiliser l'extension MySQLi ou l'extension PDO_MySQL. Voir aussi MySQL : choisir une API du guide. Alternatives à cette fonction :

Description

mysql_fetch_assoc(resource $result): array

mysql_fetch_assoc() retourne un tableau associatif qui contient la ligne lue dans le résultat result et déplace le pointeur interne de données. mysql_fetch_assoc() revient à appeler la fonction mysql_fetch_array() avec MYSQL_ASSOC en tant que second paramètre. Cette fonction retourne uniquement un tableau associatif.

Liste de paramètres

result

La ressource de résultat qui vient d'être évaluée. Ce résultat vient de l'appel à la fonction mysql_query().

Valeurs de retour

Retourne un tableau associatif de chaînes qui contient la ligne lue dans le résultat result, ou bien false s'il ne reste plus de lignes à lire.

Si plusieurs colonnes portent le même nom, la dernière aura la priorité. Pour accéder aux autres colonnes du même nom, vous devez utiliser la fonction mysql_fetch_row() avec les indices numériques ou utiliser les alias sur les noms. Regardez la documentation sur la fonction mysql_fetch_array() pour plus d'informations sur les alias.

Exemples

Exemple #1 Exemple avec mysql_fetch_assoc()

<?php

$conn
= mysql_connect("localhost", "mysql_user", "mysql_password");

if (!
$conn) {
echo
"Impossible de se connecter à la base de données : " . mysql_error();
exit;
}

if (!
mysql_select_db("mydbname")) {
echo
"Impossible de sélectionner la base mydbname : " . mysql_error();
exit;
}

$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1"
;

$result = mysql_query($sql);

if (!
$result) {
echo
"Impossible d'exécuter la requête ($sql) dans la base : " . mysql_error();
exit;
}

if (
mysql_num_rows($result) == 0) {
echo
"Aucune ligne trouvée, rien à afficher.";
exit;
}

// Tant qu'une ligne existe, place cette ligne dans la variable $row
// sous la forme d'un tableau associatif.
// Note : Si vous n'attendez qu'une seule ligne, oubliez la boucle
// Note : Si vous utilisez extract($row); dans la boucle suivante
// vous créerez $userid, $fullname et $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo
$row["userid"];
echo
$row["fullname"];
echo
$row["userstatus"];
}

mysql_free_result($result);

?>

Notes

Note: Performance

Une chose importante à noter est que l'utilisation de mysql_fetch_assoc() n'est pas significativement plus lent que l'utilisation de mysql_fetch_row(), alors qu'il fournit des valeurs significatives ajoutées.

Note: Les noms des champs retournés par cette fonction sont sensibles à la casse.

Note: Cette fonction définit les champs NULL à la valeur PHP null.

Voir aussi

  • mysql_fetch_row() - Retourne une ligne de résultat MySQL sous la forme d'un tableau
  • mysql_fetch_array() - Retourne une ligne de résultat MySQL sous la forme d'un tableau associatif, d'un tableau indexé, ou les deux
  • mysql_data_seek() - Déplace le pointeur interne de résultat MySQL
  • mysql_query() - Envoie une requête à un serveur MySQL
  • mysql_error() - Retourne le texte associé avec l'erreur générée lors de la dernière requête

add a note

User Contributed Notes 6 notes

up
5
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
5
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
18 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
-3
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
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
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);
?>
To Top