Mysql fetch assoc error

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc — Возвращает ряд результата запроса в качестве ассоциативного массива

Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:

Описание

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

Список параметров

Обрабатываемый результат запроса. Этот результат может быть получен с помощью функции mysql_query() .

Возвращаемые значения

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

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

Примеры

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

= 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_fetch_assoc() лишь незначительно медленнее, чем mysql_fetch_row() , но в то же время предоставляет важную дополнительную информацию.

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

Замечание: Эта функция устанавливает NULL-поля в значение null PHP.

Смотрите также

  • mysql_fetch_row() — Обрабатывает ряд результата запроса и возвращает массив с числовыми индексами
  • mysql_fetch_array() — Обрабатывает ряд результата запроса, возвращая ассоциативный массив, численный массив или оба
  • mysql_data_seek() — Перемещает внутренний указатель в результате запроса
  • mysql_query() — Посылает запрос MySQL
  • mysql_error() — Возвращает текст ошибки последней операции с MySQL

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.

Читайте также:  Error found dangling ssl error

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.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row ( $queryResult ) <

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 ) <

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:

—————-
// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row ( $queryResult ) <

echo $queryContent [ 0 ];
>

// Reset Our Pointer.

while( $queryContent = mysql_fetch_row ( $queryResult ) <

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.

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 );

// 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 ( «
\n Query: $sql UNsuccessful : » . mysql_error () . «\n
» );

Читайте также:  Php out memory fatal error

return ( $result ) ? true : false ;
>
?>

Источник

mysqli_result::fetch_assoc

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_assoc — mysqli_fetch_assoc — Fetch the next row of a result set as an associative array

Description

Fetches one row of data from the result set and returns it as an associative array. Each subsequent call to this function will return the next row within the result set, or null if there are no more rows.

If two or more columns of the result have the same name, the last column will take precedence and overwrite any previous data. To access multiple columns with the same name, mysqli_fetch_row() may be used to fetch the numerically indexed array, or aliases may be used in the SQL query select list to give columns different names.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP null value.

Parameters

Return Values

Returns an associative array representing the fetched row, where each key in the array represents the name of one of the result set’s columns, null if there are no more rows in the result set, or false on failure.

Examples

Example #1 mysqli_result::fetch_assoc() example

( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «world» );

$query = «SELECT Name, CountryCode FROM City ORDER BY ID DESC» ;

$result = $mysqli -> query ( $query );

/* fetch associative array */
while ( $row = $result -> fetch_assoc ()) <
printf ( «%s (%s)\n» , $row [ «Name» ], $row [ «CountryCode» ]);
>

( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$mysqli = mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );

$query = «SELECT Name, CountryCode FROM City ORDER BY ID DESC» ;

$result = mysqli_query ( $mysqli , $query );

/* fetch associative array */
while ( $row = mysqli_fetch_assoc ( $result )) <
printf ( «%s (%s)\n» , $row [ «Name» ], $row [ «CountryCode» ]);
>

The above examples will output something similar to:

Example #2 Comparison of mysqli_result iterator and mysqli_result::fetch_assoc() usage

mysqli_result can be iterated using foreach. The result set will always be iterated from the first row, regardless of the current position.

( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «world» );

$query = ‘SELECT Name, CountryCode FROM City ORDER BY ID DESC’ ;

// Using iterators
$result = $mysqli -> query ( $query );
foreach ( $result as $row ) <
printf ( «%s (%s)\n» , $row [ «Name» ], $row [ «CountryCode» ]);
>

// Not using iterators
$result = $mysqli -> query ( $query );
while ( $row = $result -> fetch_assoc ()) <
printf ( «%s (%s)\n» , $row [ «Name» ], $row [ «CountryCode» ]);
>

The above example will output something similar to:

See Also

  • mysqli_fetch_array() — Fetch the next row of a result set as an associative, a numeric array, or both
  • mysqli_fetch_column() — Fetch a single column from the next row of a result set
  • mysqli_fetch_row() — Fetch the next row of a result set as an enumerated array
  • mysqli_fetch_object() — Fetch the next row of a result set as an object
  • mysqli_query() — Performs a query on the database
  • mysqli_data_seek() — Adjusts the result pointer to an arbitrary row in the result

User Contributed Notes 5 notes

I often like to have my results sent elsewhere in the format of an array (although keep in mind that if you just plan on traversing through the array in another part of the script, this extra step is just a waste of time).

Читайте также:  Ajax request error что это

This is my one-liner for transforming a mysqli_result set into an array.
= new MySQLi ( $host , $username , $password , $database );

$result = $sql -> query ( «SELECT * FROM ` $table `;» );
for ( $set = array (); $row = $result -> fetch_assoc (); $set [] = $row );
print_r ( $set );
?>

Outputs:
Array
(
[0] => Array
(
[id] => 1
[field2] => a
[field3] => b
),
[1] => Array
(
[id] => 2
[field2] => c
[field3] => d
)
)

I use other variations to adapt to the situation, i.e. if I am selecting only one field:
= new MySQLi ( $host , $username , $password , $database );
$result = $sql -> query ( «SELECT `field2` FROM ` $table `;» );
for ( $set = array (); $row = $result -> fetch_assoc (); $set [] = $row [ ‘field2’ ]);
print_r ( $set );
?>
Outputs:
Array
(
[0] => a
[1] => c
)

Or, to make the array associative with the primary index (code assumes primary index is the first field in the table):
= new MySQLi ( $host , $username , $password , $database );
$result = $sql -> query ( «SELECT * FROM ` $table `;» );
for ( $set = array (); $row = $result -> fetch_assoc (); $set [ array_shift ( $row )] = $row );
print_r ( $set );
?>
Outputs:
Array
(
[1] => Array
(
[field2] => a
[field3] => b
),
[2] => Array
(
[field2] => c
[field3] => d
)
)

If you were used to using code like this:

while( false !== ( $row = mysql_fetch_assoc ( $result )))
<
//.
>
?>

You must change it to this for mysqli:

while( null !== ( $row = mysqli_fetch_assoc ( $result )))
<
//.
>
?>

The former will cause your script to run until max_execution_time is reached.

Be careful when using fetch_assoc instead of fetch_row. If two columns of the result have the same column name, even if they are prefixed with different table names in the query, only one of them will be retained in the result. This is because the prefix is dropped (either by mysql or by this function)

For example if the query is

select p1.name, p2.name
from person p1, friend, person p2
where p1.id = friend.person1 and p2.id = friend.person2

the arrays returned by fetch_assoc will be of the form

and not (as expected)

when you fetch the data from the query variable
and try to fetch it again in another part of the script
from the same query variable ,
when you try to echo all data you have fetched,
it will not echo the data you have used in the first fetch
(it will exceed the results you have used in the first fetch).

Example :
= new mysqli ( «localhost» , «root» , «root» , «elshamy» )
or die ( mysqli_error ());

$query = $connect -> query ( «SELECT * FROM users ORDER BY id ASC» );

$first_fetch = $query -> fetch_array ( MYSQLI_ASSOC );
echo $first_fetch [ ‘id’ ]. «===>» . $first_fetch [ ‘user_name’ ]. «\n———————\n» ;

while( $row = $query -> fetch_array ( MYSQLI_ASSOC ))<

/*it will exceed the first
id&user_name value that
you have use in the first fetch*/

The official example given here breaks a cardinal rule, and should be rectified.

while ($row = $result->fetch_assoc()).

. breaks the rule of «assignment in condition».

while (($x = $y->getZ()) !== false) or
while (($x = $y->getZ()) !== null)

. is the correct syntax.

Conditional statements should always check for a boolean

Источник

Smartadm.ru
Adblock
detector