(PHP 4 >= 4.0.3, PHP 5)
mysql_fetch_assoc — 从结果集中取得一行作为关联数组
$result
)
返回根据从结果集取得的行生成的关联数组,如果没有更多行则返回 FALSE
。
mysql_fetch_assoc() 和用 mysql_fetch_array() 加上第二个可选参数 MYSQL_ASSOC 完全相同。它仅仅返回关联数组。这也是 mysql_fetch_array() 起初始的工作方式。如果在关联索引之外还需要数字索引,用 mysql_fetch_array()。
如果结果中的两个或以上的列具有相同字段名,最后一列将优先。要访问同名的其它列,要么用 mysql_fetch_row() 来取得数字索引或给该列起个别名。参见 mysql_fetch_array() 例子中有关别名说明。
有一点很重要必须指出,用 mysql_fetch_assoc() 并不明显 比用 mysql_fetch_row() 慢,而且还提供了明显更多的值。
Note: 此函数返回的字段名大小写敏感。
Example #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;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $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()。
Returns an associative array of strings that corresponds to the fetched row, or
FALSE
if there are no more rows.
If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysql_fetch_row() or add alias names. See the example at the mysql_fetch_array() description about aliases.
Example #2 An expanded mysql_fetch_assoc() example
<?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;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
?>
Note: Performance
An important thing to note is that using mysql_fetch_assoc() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value.
Note: 此函数返回的字段名大小写敏感。
Note: 此函数将 NULL 字段设置为 PHP
NULL
值。
andy dot g dot mac at gmail dot com (2011-12-30 13:30:41)
If you use the MySQL MAX() function as part of your query, reference it with, for example:
<?php
$ID = $result['MAX(ID)'];
?>
not
<?php
$ID = $result['MAX(`ID`)'];
?>
as I tried ... I hope that saves someone a few minutes ...
Gorm (2011-12-28 04:10:16)
A function to retrieve _all_ fields as fully qualified names:
<?php
function mysql_fetch_assoc_fullname($r)
{
// Does the same thing a as mysql_fetch_assoc, but the keys are fully qualified like <table name>.<field name>.
// That way all fields is perserved and adressable like mysql_fetch_row is.
// table name will be blank if its a computed field. F.ex: 'select 5+5 as ten' will give array('.ten' => 10)
$f = mysql_fetch_row($r);
if($f === false) return false;
$tmp = array();
foreach($f as $k => $v)
{
$tmp[mysql_field_table($r, $k) . '.' . mysql_field_name($r, $k)] = $v;
}
return $tmp;
}
?>
george at georgefisher dot com (2009-04-21 07:51:35)
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;
}
?>
Daniel Chcouri - 333222 +A-T+ gmail (2009-04-02 03:45:17)
Fetching all the results to array with one liner:
<?php
$result = mysql_query(...);
while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
?>
josh at joshstrike dot com (2008-12-27 03:40:32)
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);
}
?>
alx at inbox dot lv (2008-03-31 16:36:47)
Alternate option for mysqk_fetch_assoc
I spent a day thinking.. damn!
<?php
function &dbFetch(&$result) {
dbTimeOn();
if ($EOF) $rs = false;
else {
dbMoveNext($result,$fields,$EOF);
$rs = $fields;
}
dbTimeOff();
return $rs;
}
function &dbMoveNext(&$result,&$fields,&$EOF) {
if ($fields =& mysql_fetch_array($result,MYSQL_ASSOC)) {
return true;
}
if (!$EOF) {
$EOF = true;
}
return false;
}
?>
Hope it willl help someone.
nick at homefeedback dot com (2007-03-21 16:50:25)
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." ";
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." ";
echo "</td>\n";
next($curr_row);
$col++;
}
while($col <= $num){
echo "<td> </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
?>
Typer85 at gmail dot com (2006-11-30 17:21:26)
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.
AK-Palme (2006-11-27 08:14:18)
This is a fetch-function useful while using multiple tables in your query:
function sqlf($result){
$row = mysql_fetch_row($result);
if($row === FALSE) return FALSE;
for ($i = 0; $i < mysql_num_fields($result); $i++) {
$meta = mysql_fetch_field($result, $i);
$data[$meta ->table . '.' . $meta->name] = $row[$i];
}
return $data;
}
the result will be an array containing fields like this:
[table.field] => value
JPM (2006-10-28 01:00:26)
For the last post, I thing there is a little mistake :
the second
if (count($columns)>0)
should be
if (count($values)>0)
By the way, thx for this useful function.
(2006-10-16 12:05:21)
I just fixed some things in my own mysql_insert_assoc - I used it in development and just noticed things that went wrong...
<?php
class MySQL {
static $link = NULL;
static function uncached_insert ($table, $values) {
// Find all the keys (column names) from the array $my_array
$columns = array_keys($values);
// Find all the values from the array
var_export($columns);
reset($values);
while (list($key, $val) = each($values)) {
$values[$key] = mysql_real_escape_string($val,self::$link);
}
// We compose the query
$sql = 'INSERT INTO `'.$table.'` ';
// implode the column names, inserting '`, `' between each
// we add the enclosing quotes at the same time
if (count($columns)>0) {
$sql .= '(`' . implode('`, `', $columns) . '`)';
}
$sql .= ' VALUES ';
// Same with the values
if (count($columns)>0) {
$sql .= '(\'' . implode('\', \'', $values) . '\')';
} else {
$sql .= '()';
}
$result = mysql_query($sql,self::$link);
var_export($sql);
if (!$result) echo 'The row was not added<br>The error was ' . mysql_error();
return $result;
}
}
?>
Unfortunately it looks way different from what I had before (because I copied it from my program), but it fixes these bugs:
- fields MUST have backticks, no single quotes
- empty arrays did trouble
- space after the error echo
q-tech at phreaker dot net (2006-09-21 03:18:52)
In regards to Maviee's fetch function I suggest a more functional approach:
<?php
function msq($q)
{
global $dbqcount; //Count queries for the page;
$dbqcount++;
if (!$res=mysql_query ($q)) die (mysql_error());
$rr[0]=0; //$rr[0] countains number of the returned results
if (is_resource($res))
{
while ($rr[]=mysql_fetch_assoc($res)) $rr[0]++;
mysql_free_result($res);
}
return $rr;
}
?>
Also I would like to point out that mysql_fetch_assoc does associate array EXACTLY to the name of the fields/functions you've recieved results for! E.g.:
<?php
$rez=msq("SELECT MAX(`ID`) FROM `table1`"); // $rez will contain assoc. variable named $rez[1]['MAX(`ID`)'], not $rez[1]['ID']
?>
R. Bradley (2006-09-14 08:34:19)
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")
Sergiu (2006-08-31 07:01:21)
A function, fully commented, for inserting an associative array into a table.
<?php
function mysql_insert_assoc ($my_table, $my_array) {
// Find all the keys from the array $my_array
$keys = array_keys($my_array);
// Find the number of the keys
$keys_number = count($keys);
// Generate the column name for the $sql query
$column_names = "(";
$values = "(";
for ($i = 0; $i < $keys_number; $i++) {
$column_name = $keys[$i];
// We don't add "," after the last one
if ($i == ($keys_number - 1)) {
$column_names .= "`$keys[$i]`";
$values .= "'$my_array[$column_name]'";
} else {
$column_names .= "`$keys[$i]`" . ", ";
$values .= "'$my_array[$column_name]'" . ", ";
}
}
// Proper end the column name and the value
$column_names .= ")";
$values .= ")";
// We compose the query
$sql = "insert into `$my_table` ";
$sql .= $column_names;
$sql .= ' values ';
$sql .= $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;
}
}
?>
rinke van den berg (2006-07-30 02:42:09)
I read someone posting 'I have the philosphy that a function has exactly one return point.'
It seems to me that always having only one return point takes away a little power from 'return' making code less efficient. Compare:
function doSomething($a,$b) {
$returnVal = 1;
if($a==$b) { $returnVal = false; }
if($returnVal !== false) { //didnt we discover that already?
//do something as we know a and b is what we expect
$returnVal = $a - $b;
}
return $returnVal;
}
with:
function doSomething($a,$b) {
if($a==$b) { return false; //early exit }
//do something as we know a and b is what we expect
return $a-$b;
}
paintedgauthier at gmail dot com (2006-03-04 01:49:45)
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 (2006-02-23 11:26:14)
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 (2006-02-01 21:22:31)
Note that the field names quoted within $row[] are case sensitive whereas many sql commands are case insensitive.
Maviee at gmx dot net (2006-01-13 02:38:32)
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;
}
(2005-12-13 15:25:36)
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);
(2005-10-08 19:03:19)
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." ";
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." ";
echo "</td>\n";
next($curr_row);
$col++;
}
while($col <= $num){
echo "<td> </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 (2005-08-23 16:25:52)
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 (2005-06-21 01:58:00)
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 (2005-05-14 12:50:09)
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 (2004-09-29 01:07:37)
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 (2004-09-17 05:27:53)
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 (2003-09-04 16:57:49)
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>";
}