mysql_fetch_assoc
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
Description
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.
Parameters
The result resource that is being evaluated. This result comes from a call to mysql_query() .
Return Values
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.
Examples
Example #1 An expanded mysql_fetch_assoc() example
$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″ ;
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» ];
>
Notes
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: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP null value.
See Also
- mysql_fetch_row() — Get a result row as an enumerated array
- mysql_fetch_array() — Fetch a result row as an associative array, a numeric array, or both
- mysql_data_seek() — Move internal result pointer
- mysql_query() — Send a MySQL query
- mysql_error() — Returns the text of the error message from previous MySQL operation
User Contributed Notes 15 notes
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 «
userid: $row[‘uID’], orderid: $row[‘oID’]
«;
>
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!?
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.
// Assume We Already Queried Our Database.
while( $queryContent = mysql_fetch_row ( $queryResult )
// 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 )
// 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:
// Assume We Already Queried Our Database.
while( $queryContent = mysql_fetch_row ( $queryResult )
while( $queryContent = mysql_fetch_row ( $queryResult )
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.
Thanks to to R. Bradley for the implode idea. The following fixes a few bugs and includes quote_smart functionality (and has been tested)
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)
//
// 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 );
// 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 ( «
\nQuery: $sql UNsuccessful : » . mysql_error () . «\n
» );
return ( $result ) ? true : false ;
>
?>
mysql_fetch_assoc
Данное расширение устарело, начиная с версии PHP 5.5.0, и будет удалено в будущем. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API и соответствующий FAQ для получения более подробной информации. Альтернативы для данной функции:
Описание
Возвращает ассоциативный массив, соответствующий полученному ряду и сдвигает вперед внутренний указатель результата. Функция mysql_fetch_assoc() аналогична вызову функции mysql_fetch_array() со вторым необязательным параметром, равным MYSQL_ASSOC. Функция возвращает только ассоциативный массив.
Список параметров
Обрабатываемый результат запроса. Этот результат может быть получен с помощью функции mysql_query() .
Возвращаемые значения
Возвращает ассоциативный массив строк, соответствующий полученному ряду, либо FALSE если рядов больше нет.
Если два или более столбцов результата имеют одинаковые имена, приоритет будет иметь последний столбец. Для доступа к другому одноименному столбцу (или столбцам), вам необходимо либо обратиться к результату запроса по числовому индексу с помощью mysql_fetch_row() либо добавить псевдонимы к нужным столбцам. Для более подробной информации о псевдонимах смотрите описание примера mysql_fetch_array() .
Примеры
Пример #1 Расширенный пример использования mysql_fetch_assoc()
$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″ ;
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_fetch_assoc() лишь незначительно медленнее, чем mysql_fetch_row() , но в то же время предоставляет важную дополнительную информацию.
Замечание: Имена полей, возвращаемые этой функцией являются регистро-зависимыми.
Замечание: Эта функция устанавливает NULL-поля в значение NULL PHP.
Смотрите также
- mysql_fetch_row() — Обрабатывает ряд результата запроса и возвращает массив с числовыми индексами
- mysql_fetch_array() — Обрабатывает ряд результата запроса, возвращая ассоциативный массив, численный массив или оба
- mysql_data_seek() — Перемещает внутренний указатель в результате запроса
- mysql_query() — Посылает запрос MySQL
- mysql_error() — Возвращает текст ошибки последней операции с MySQL
mysqli_fetch_assoc
Возвращает ассоциативный массив, соответствующий результирующей выборке или NULL , если других рядов не существует.
Замечание: Имена полей, возвращаемые этой функцией являются регистро-зависимыми.
Замечание: Эта функция устанавливает NULL-поля в значение NULL PHP.
Список параметров
Только для процедурного стиля: Идентификатор результата запроса, полученный с помощью mysqli_query() , mysqli_store_result() или mysqli_use_result() .
Возвращаемые значения
Возвращает ассоциативный массив строк, соответствующий результирующей выборке, где каждый ключ в массиве соответствует имени одного из столбцов выборки или NULL , если других рядов не существует.
Если два или более столбца в выборке имеют одинаковое название полей, то приоритет отдается последнему столбцу. Для доступа к другому столбцу с таким же именем вам необходимо произвести нумерованную выборку с помощью функцию mysqli_fetch_row() или добавить псевдонимы.
Примеры
Пример #1 Объектно-ориентированный стиль
$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «world» );
?php
/* проверка соединения */
if ( $mysqli -> connect_errno ) printf ( «Соединение не удалось: %s\n» , $mysqli -> connect_error );
exit();
>
$query = «SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5» ;
if ( $result = $mysqli -> query ( $query ))
/* извлечение ассоциативного массива */
while ( $row = $result -> fetch_assoc ()) printf ( «%s (%s)\n» , $row [ «Name» ], $row [ «CountryCode» ]);
>
/* удаление выборки */
$result -> free ();
>
/* закрытие соединения */
$mysqli -> close ();
?>
Пример #2 Процедурный стиль
$link = mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );
?php
/* проверка соединения */
if ( mysqli_connect_errno ()) printf ( «Соединение не удалось: %s\n» , mysqli_connect_error ());
exit();
>
$query = «SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5» ;
if ( $result = mysqli_query ( $link , $query ))
/* извлечение ассоциативного массива */
while ( $row = mysqli_fetch_assoc ( $result )) printf ( «%s (%s)\n» , $row [ «Name» ], $row [ «CountryCode» ]);
>
/* удаление выборки */
mysqli_free_result ( $result );
>
/* закрытие соединения */
mysqli_close ( $link );
?>
Результат выполнения данных примеров:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA)
Пример #3 Пример mysqli_result с использованием класса iterator
$c = mysqli_connect ( ‘127.0.0.1’ , ‘user’ , ‘pass’ );
?php
// Использование итераторов (поддержка была добавлена начиная с PHP 5.4)
foreach ( $c -> query ( ‘SELECT user,host FROM mysql.user’ ) as $row ) printf ( «‘%s’@’%s’\n» , $row [ ‘user’ ], $row [ ‘host’ ]);
>
// Без использования итераторов
$result = $c -> query ( ‘SELECT user,host FROM mysql.user’ );
while ( $row = $result -> fetch_assoc ()) printf ( «‘%s’@’%s’\n» , $row [ ‘user’ ], $row [ ‘host’ ]);
>
Результатом выполнения данного примера будет что-то подобное:
'root'@'192.168.1.1' 'root'@'127.0.0.1' 'dude'@'localhost' 'lebowski'@'localhost' ================== 'root'@'192.168.1.1' 'root'@'127.0.0.1' 'dude'@'localhost' 'lebowski'@'localhost'
Смотрите также
- mysqli_fetch_array() — Выбирает одну строку из результирующего набора и помещает ее в ассоциативный массив, обычный массив или в оба
- mysqli_fetch_row() — Получение строки результирующей таблицы в виде массива
- mysqli_fetch_object() — Возвращает текущую строку результирующего набора в виде объекта
- mysqli_query() — Выполняет запрос к базе данных
- mysqli_data_seek() — Перемещает указатель результата на выбранную строку