Mysql fetch array не работает

Не работает mysql_fetch_array

Есть таблица users, в ней две колонки — id и login. Для примера, первая запись — id 1, login 7433. Нужно через форму принять значение логина и на его основе делать всякие действия. Значение логина записывается в переменную $playerNumber. С этим вроде все нормально. Пишу запрос:

Как писать нужные мне действия я вроде понимаю, но выводится не та информация, которая нужна (но то, что она вообще выводится — это хорошо, хотя бы коннект с базой работает). Проверяла, добавляя var_dump($result) после третьей строчки в примере выше, пишет — bool(false). Может, у кого есть какие мысли, почему mysql_fetch_array не пишет в $result?

1 ответ 1

Да бросьте вы уже mysql-расширение. Оно устарело и даже удалено из новых версий PHP.

При изучении PHP используйте документацию PHP, она очень неплохая и переведена на русский язык. Документация находится на сайте php.net, зайдите в описание функции mysql_query. Первое что бросается в глаза — предупреждение о том, что функция устарела и использовать её не надо. Кроме того, предлагается две альтернативы mysqli и PDO.

Интерфейс mysqli похож на интерфейс mysql-расширения и возможно вам будет проще начать с него. Открывайте ссылку mysqli_query, прочитайте описание и загляните в примеры использования. Там будут ответы на самые первые ваши вопросы!

Читайте также:  Как настроить джойстик assetto corsa

Когда вы разберётесь как делать запросы к базе данных и обрабатывать полученные результаты, обязательно обратите внимание на то, что подставлять неэкранированные значения в SQL-запрос опасно. Погуглите SQL-инъекция .

Конкретно в вашем случае false означает, что ничего не найдено по вашему запросу. Убедитесь что он составлен верно сделайте var_dump(«SELECT * FROM users WHERE login=’$playerNumber'»);

Источник

Mysql fetch array не работает

Здравствуйте, уважаемые коллеги! Я новичок в программировании, на данный момент учусь по учебнику. Появилась такая проблема.
Сразу даю код:

Вот тут кроется какая-то логическая ошибка, ибо интерпретатор php не ругается, и в браузере ошибок никаких нет. А вот слово «Ошибка» браузер выводит. И из-за этого я не могу организовать динамический вывод информации из БД.

Очень надеюсь на вашу помощь.

lisdrumz
Интересно, назови имя учебника, очень хочется узнать, по какому такому учебнику учился Попов
Ах да, Попов рассказывал, что делает функция: mysql _fetch_array, она перещёлкивает на +1 значение. Если выбралось 1 запись. Ты запустил mysql _fetch_array дважды, второй раз вернул FALSE mysql _fetch_array дважды

Да почему же, никак понять не могу.

$myrow = mysql _fetch_array($result); — первый раз!
if($myrow = mysql _fetch_array($result)) — второй раз!

Условие звучит так: мы запустили то, что в скобках, результат скобок проверяется, прошел ли он: TRUE\FALSE

и посмотри есть ли там что нибудь или нет

Сделал. И попытался сразу после этого вывести ещё одно значение. Получилось так:

Вывело такое: bool(false)

Странно, вроде всё делаю, как показывают, в чём же проблема?

lisdrumz
Глянь ссылки у меня в подписи, после Попова очень полезно бывает

Ответ в том, что ты использовал одинарные кавычки. Вот пример:
$var = ‘ПИВО!’; // ты же любишь пиво?
echo «Я люблю $var , оно вкусное \n\rА это уже новая строка»;
echo ‘ ‘;
echo ‘Я люблю $var , оно вкусное \n\rА это уже новая строка’;

Теперь открывай исходный код и смотри разницу, понимаешь свою ошибку? Ошибка в выборе кавычек, те кавычки не интерпретируются. Если уж вообще правильно писать — так, как пишет Линкер.

lisdrumz
Ну что я могу сказать. Представь картину, мой брат помогает своему лучшему другу с дипломом, так как он мало знает программирование, пару курсов тянет, даёт списать, все получают красивую корочку, красивые блондинки 5+, крутые программисты тянут с трудом на 4-, мой брат поступает работать администратором сетей за приличную з/п, его друг, о котором ранее говорил, находит работу в «Академии Шаг», единственная академия, где учат всему для веба. Вот и подумай, преподают, а какие у них знания, если она работают на гос. учереждении за гос.зарплату для студентов?
Вот так и там, пока один пыхтит в месяц на 300-500$, другой за месяц делает 10`000$, и можно ли утверждать, что 300$ в университете препод имеет знания выше, чем тот, кто работает по настоящему, где контроль за его знаниями осуществляет жизнь?!

Хотя как альтернативу могу сказать вот что: человек, прочитавший 5 книг будет умнее того, кто прочитал всего 1 книгу. Очевидно, что надо, но лучше после Попова изучать по данным направлениям: наш форум, учебник Котерова, irbis-team.com , mysql .ru , ну и реальная практика на сайтах.

Я путаюсь между специалистом и профессионалом, но один из курсов — ужасный

Цитата (inpost @ 17.06.2011 — 12:58)
irbis-team.com

Это вообще офигительный сайт, сразу себе в закладки добавил! Всё очень сжато, чётко, без воды, и главное — конкретно, много кода. Класс!

Цитата (inpost @ 17.06.2011 — 12:58)
Я путаюсь между специалистом и профессионалом, но один из курсов — ужасный

А какой точно — никак не сможете вспомнить или узнать?

Цитата (lisdrumz @ 17.06.2011 — 13:01)
по поводу курса, ничего не могу сказать, ибо ссылка не работает.

Странно — у меня ссылка работает.
А так, не вспомните — курс «Профессионал PHP»?

Источник

Особенности работы функции mysql_fetch_array

Получил список таблиц из БД. Но работать с этими данными не получается.

Проблема в том, что этот код работает(выводится информация):

А этот нет(НЕ выводится информация):

Что я делаю не так, объясните?

2 ответа 2

Особенностью функции mysql_fetch_array() и вообще все курсорных функций является то, что они извлекая строку из результирующей таблицы продвигают курсор вперед. Поэтому если у вас в таблице лишь две записи и вы два раза вызываете mysql_fetch_array() , то последующие вызовы ни к чему не приводят, так как курсор указывает на конец результирующей таблицы. Для того, чтобы установить курсор в начало, вам потребуется выполнить функцию mysql_data_seek() .

mysql_fetch_array — Обрабатывает ряд результата запроса, возвращая ассоциативный массив, численный массив или оба.Возвращает массив, соответствующий обработанному ряду результата запроса и сдвигает внутренний указатель данных вперед. Это означает что надо пользоваться этой возможностью.То Есть бросить ее в цикл который при каждой итераций будет передвигать внутренний курсор в перед.возвращать либо данное значение либо false если курсор дошел до конца.

Без цикла,то есть присвоив ее переменной (в вашем случае) мы получим текущее одно значение массива.

Для понимания что такое курсор в массивах изучи функции next(), current(),prev(),reset(),end()

Всё ещё ищете ответ? Посмотрите другие вопросы с метками php mysql sql или задайте свой вопрос.

Похожие

Подписаться на ленту

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.10.15.40479

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Источник

Как исправить ошибку запроса через mysqli_fetch_array?

При выполнении приведенного ниже куска кода возникает следующая ошибка:

Подскажите, как с этим бороться?
Сам запрос верный и возвращает строку с результатом.

  • Вопрос задан более двух лет назад
  • 200 просмотров

Получилось разобраться, ошибка крылась в методе:

Проверять надо, что находится в $result.

Сам запрос верный и возвращает строку с результатом

Эта ошибка возникает, если запрос не может быть выполнен. Лично мне запрос вообще не нравится, особенно этот кусок:

А тут потенциальная угроза SQL-injection

В первом куске все ОК, там просто подставляется имя базы данных.
Даже, если я заменю переменную и впишу имя Базы руками, ничего не изменится (ошибка остается).

Защита от инъекций присутствует, это всего лишь кусок кода. Все «зачищается» перед запросом.

Источник

mysql_fetch_array

mysql_fetch_array — Обрабатывает ряд результата запроса, возвращая ассоциативный массив, численный массив или оба

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

Описание

Возвращает массив, соответствующий обработанному ряду результата запроса и сдвигает внутренний указатель данных вперёд.

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

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

Тип возвращаемого массива. Является константой и может принимать следующие значения: MYSQL_ASSOC , MYSQL_NUM и MYSQL_BOTH .

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

Возвращает массив строк, соответствующих обработанному ряду результата запроса, или false , если рядов больше нет. Тип возвращаемого массива зависит от значения параметра result_type . При использовании MYSQL_BOTH (по умолчанию), вы получите массив, состоящий как из ассоциативных индексов, так и из численных. MYSQL_ASSOC вернёт только ассоциативные индексы (аналогично функции mysql_fetch_assoc() ), а MYSQL_NUM — только численные (аналогично функции mysql_fetch_row() ).

Если несколько колонок в результате будут иметь одинаковые названия, то будет возвращена последняя колонка. Чтобы получить доступ к другим колонкам с тем же именем, используйте численные индексы массива или псевдонимы в запросе. В случае псевдонимов используйте именно их — вы не сможете использовать настоящие имена колонок.

Примеры

Пример #1 Запрос с применением псевдонимов для дублирующихся имён колонок

Пример #2 mysql_fetch_array() с MYSQL_NUM

( «localhost» , «mysql_user» , «mysql_password» ) or
die( «Ошибка соединения: » . mysql_error ());
mysql_select_db ( «mydb» );

$result = mysql_query ( «SELECT id, name FROM mytable» );

while ( $row = mysql_fetch_array ( $result , MYSQL_NUM )) <
printf ( «ID: %s Имя: %s» , $row [ 0 ], $row [ 1 ]);
>

Пример #3 mysql_fetch_array() с MYSQL_ASSOC

( «localhost» , «mysql_user» , «mysql_password» ) or
die( «Ошибка соединения: » . mysql_error ());
mysql_select_db ( «mydb» );

$result = mysql_query ( «SELECT id, name FROM mytable» );

while ( $row = mysql_fetch_array ( $result , MYSQL_ASSOC )) <
printf ( «ID: %s Имя: %s» , $row [ «id» ], $row [ «name» ]);
>

Пример #4 mysql_fetch_array() с MYSQL_BOTH

( «localhost» , «mysql_user» , «mysql_password» ) or
die( «Ошибка соединения: » . mysql_error ());
mysql_select_db ( «mydb» );

$result = mysql_query ( «SELECT id, name FROM mytable» );

while ( $row = mysql_fetch_array ( $result , MYSQL_BOTH )) <
printf ( «ID: %s Имя: %s» , $row [ 0 ], $row [ «name» ]);
>

Примечания

Замечание: Производительность

Важно заметить, что mysql_fetch_array() работает незначительно медленнее, чем mysql_fetch_row() , в то же время предоставляя намного более удобный доступ к данным.

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

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

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

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

User Contributed Notes 31 notes

Benchmark on a table with 38567 rows:

mysql_fetch_array
MYSQL_BOTH: 6.01940000057 secs
MYSQL_NUM: 3.22173595428 secs
MYSQL_ASSOC: 3.92950594425 secs

mysql_fetch_row: 2.35096800327 secs
mysql_fetch_assoc: 2.92349803448 secs

As you can see, it’s twice as effecient to fetch either an array or a hash, rather than getting both. it’s even faster to use fetch_row rather than passing fetch_array MYSQL_NUM, or fetch_assoc rather than fetch_array MYSQL_ASSOC. Don’t fetch BOTH unless you really need them, and most of the time you don’t.

I have found a way to put all results from the select query in an array in one line.

// Read records
$result = mysql_query(«SELECT * FROM table;») or die(mysql_error());

// Put them in array
for($i = 0; $array[$i] = mysql_fetch_assoc($result); $i++) ;

// Delete last empty one
array_pop($array);

You need to delete the last one because this will always be empty.

By this you can easily read the entire table to an array and preserve the keys of the table columns. Very handy.

For all of you having problems accessing duplicated field names in queries with their table alias i have implemented the following quick solution:

function mysql_fetch_alias_array ( $result )
<
if (!( $row = mysql_fetch_array ( $result )))
<
return null ;
>

$assoc = Array();
$rowCount = mysql_num_fields ( $result );

for ( $idx = 0 ; $idx $rowCount ; $idx ++)
<
$table = mysql_field_table ( $result , $idx );
$field = mysql_field_name ( $result , $idx );
$assoc [ » $table . $field » ] = $row [ $idx ];
>

return $assoc ;
>
?>

Lets asume we have 2 tables student and contact each having fID as the index field and want to access both fID fields in php.

The usage of this function will be pretty similar to calling mysql_fetch_array:

= mysql_query ( «select * from student s inner join contact c on c.fID = s.frContactID» );

while ( $row = mysql_fetch_alias_array ( $result ))
<
echo «StudenID: < $row [ 's.fID' ]>, ContactID: < $row [ 'c.fID' ]>» ;
>
?>

Voila, that’s it 🙂

Please be aware that by using this function, you have to access all fields with their alias name (e.g. s.Name, s.Birhtday) even if they are not duplicated.

If you have questions, just send me a mail.

Best regards,
Mehdi Haresi
die-webdesigner.at

Regarding duplicated field names in queries, I wanted some way to retrieve rows without having to use alias, so I wrote this class that returns rows as 2d-arrays

Here is the code:

results = $results;
$this->map = array();

$index = 0;
while ($column = mysql_fetch_field($results))
<
$this->map[$index++] = array($column->table, $column->name);
>
>

function fetch()
<
if ($row = mysql_fetch_row($this->results))
<
$drow = array();

foreach ($row as $index => $field)
<
list($table, $column) = $this->map[$index];
$drow[$table][$column] = $row[$index];
>

The class is initialized with a mysql_query result:

The constructor builds an array that maps each field index to a ($table, $column) array so we can use mysql_fetch_row and access field values by index in the fetch() method. This method then uses the map to build up the 2d-array.

I hope others find this useful as it has been to me.

Simple way to put table in an array.

//= Query ========================//
$sql = mysql_query ( «select * from table1» );

//= Closed while ====================//
/*everytime it fetches the row, adds it to array. */
while( $r []= mysql_fetch_array ( $sql ));

One of the most common mistakes that people make with this function, when using it multiple times in one script, is that they forget to use the mysql_data_seek() function to reset the internal data pointer.

When iterating through an array of MySQL results, e.g.

while ( $line = mysql_fetch_array ( $result , MYSQL_ASSOC )) <
foreach ( $line as $col_value ) <
echo $col_value . ‘
‘ ;
>
>
?>

the internal data pointer for the array is advanced, incrementally, until there are no more elements left in the array. So, basically, if you copy/pasted the above code into a script TWICE, the second copy would not create any output. The reason is because the data pointer has been advanced to the end of the $line array and returned FALSE upon doing so.

If, for some reason, you wanted to interate through the array a second time, perhaps grabbing a different piece of data from the same result set, you would have to make sure you call

( $result , 0 );
?>

This function resets the pointer and you can re-iterate through the $line array, again!

for the problem with fields containing null values in an associated array, feel free to use this function. i’ve got no more problems with it, just drop it in your script:

/*
* mysql_fetch_array_nullsafe
*
*
* get a result row as an enumerated and associated array
* ! nullsafe !
*
* parameter: $result
* $result: valid db result id
*
* returns: array | false (mysql:if there are any more rows)
*
*/
function mysql_fetch_array_nullsafe($result) <
$ret=array();

$num = mysql_num_fields($result);
if ($num==0) return $ret;

$fval = mysql_fetch_row ($result);
if ($fval === false) return false;

Just another workaround for columns with duplicate names.

Modify your SQL to use the AS keyword.

Instead of:
$sql = «SELECT t1.cA, t2.cA FROM t1, t2 WHERE t1.cA = t2.cA»;

Try:
$sql = «SELECT t1.cA AS foo1, t2.cA AS foo2 FROM t1, t2 WHERE t1.cA = t2.cA»;

Then you can reference the results by name in the array:
$row[foo1], $row[foo2]

Here’s a quicker way to clone a record. Only 3 lines of code instead of 4. But the table must have an auto-incremented id.
I took the code from Tim and altered it. Props to Tim.

// copy content of the record you wish to clone
$entity = mysql_fetch_array ( mysql_query ( «SELECT * FROM table_name WHERE > $id_to_be cloned'» ), MYSQL_ASSOC ) or die( «Could not select original record» );

// set the auto-incremented id’s value to blank. If you forget this step, nothing will work because we can’t have two records with the same id
$entity [ «id» ] = «» ;

// insert cloned copy of the original record
mysql_query ( «INSERT INTO table_name (» . implode ( «, » , array_keys ( $entity )). «) VALUES (‘» . implode ( «‘, ‘» , array_values ( $entity )). «‘)» );

// if you want the auto-generated id of the new cloned record, do the following
$newid = mysql_insert_id ();
?>

There you go.

I did find ‘jb at stormvision’s’ code useful above, but instead of the number of rows you need the number of fields; otherwise you get an error.

So, it should read like the following:

$result=mysql_query(«select * from mydata order by ‘id'»)or die(‘died’);
$num_fields = mysql_num_fields($result);
$j=0;
$x=1;
while($row=mysql_fetch_array($result)) <
for($j=0;$j

while( $r []= mysql_fetch_array ( $sql ));
?>

so in array $r is one more entry then rows returned from the database.

In the note entered by Typer85, concerning the use of mysql_data_seek(), it should be noted that there are two parameters, both of which are required.

If you have already iterated through a result array (for instance, using mysql_fetch_array()), and have a need to start from the top, the proper syntax is:

EG:
mysql_data_seek($result,0)
(«0» represents the first record in the array.)

This will reset your result to the top of the array so that you can then re-process with
while($row = mysql_fetch_array($result)) or other array processing.

Little improvement to the previous function.

function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) <
$got = array();

if(mysql_num_rows($result) == 0)
return $got;

while ($row = mysql_fetch_array($result, $numass)) <
array_push($got, $row);
>

my main purpose was to show the fetched array into a table, showing the results side by side instead of underneath each other, and heres what I’ve come up with.

just change the $display number to however many columns you would like to have, just dont change the $cols number or you might run into some problems.

= 4 ;
$cols = 0 ;
echo »

» ;
while( $fetched = mysql_fetch_array ( $result )) <
if( $cols == 0 ) <
echo » \n» ;
>
// put what you would like to display within each cell here
echo »

\n» ;
$cols ++;
if( $cols == $display ) <
echo «

\n» ;
$cols = 0 ;
>
>
// added the following so it would display the correct html
if( $cols != $display && $cols != 0 ) <
$neededtds = $display — $cols ;
for( $i = 0 ; $i $neededtds ; $i ++) <
echo » \n» ;
>
echo «

» . $fetched [ ‘id’ ]. «
» . $fetched [ ‘name’ ]. «

» ;
> else <
echo «

» ;
>
?>

Hopefully this will save some of you a lot of searching.

any kind of improvements on this would be awesome!

I ran into troubles with MySQL NULL values when I generated dynamic queries and then had to figure out whether my resultset contained a specific field.

First instict was to use isset() and is_null(), but these function will not behave as you probably expect.

I ended up using array_key_exists, as it was the only function that could tell me whether the key actually existed or not.

= mysql_fetch_assoc ( mysql_query ( «SELECT null as a» ));
var_dump ( $row ); //array(1) < ["a"]=>NULL >
var_dump (isset( $row [ ‘a’ ])); //false
var_dump (isset( $row [ ‘b’ ])); //false
var_dump ( is_null ( $row [ ‘a’ ])); //true
var_dump ( is_null ( $row [ ‘b’ ])); //true + throws undefined index notice
var_dump ( array_key_exists ( ‘a’ , $row )); // true
var_dump ( array_key_exists ( ‘b’ , $row )); // false
?>

It’s kind of similar to Daogen, which was suggested in one of the comments above, but simpler and easier to use.

Php Object Generator generates the Php Classes for your Php Objects. It also provides the database class so you can focus on more important aspects of your project. Hope this helps.

As opposite of mysql_fetch_array:

function mysql_insert_array ( $my_table , $my_array ) <
$keys = array_keys ( $my_array );
$values = array_values ( $my_array );
$sql = ‘INSERT INTO ‘ . $my_table . ‘(‘ . implode ( ‘,’ , $keys ) . ‘) VALUES («‘ . implode ( ‘»,»‘ , $values ) . ‘»)’ ;
return( mysql_query ( $sql ));
>
#http://www.weberdev.com/get_example-4493.html
?>

Here is a suggestion to workaround the problem of NULL values:

// get associative array, with NULL values set
$record = mysql_fetch_array($queryID,MYSQL_ASSOC);

// set number indices
if(is_array($record))
<
$i = 0;
foreach($record as $element)
$record[$i++] = $element;
>

This way you can access $result array as usual, having NULL fields set.

mob AT stag DOT ru has a nice function for getting simple arrays from MySQL but it has a serious bug. The MySQL link being set as an argument is NULL when no link is supplied meaning that you’re passing NULL to the mysql funcctions as a link, which is wrong. I am not using multitple connections so I removed the link and using the global link. If you want to support multiple links check to see if its set first.

/*
* to support multiple links add the $link argument to function then
* test it before you use the link
*
* if(isset($link))
* if($err=mysql_errno($link))return $err;
* else
* if($err=mysql_errno())return $err;
*/

function mysql_fetch_all($query) <
$r=@mysql_query($query);
if($err=mysql_errno())return $err;
if(@mysql_num_rows($r))
while($row=mysql_fetch_array($r))$result[]=$row;
return $result;
>
function mysql_fetch_one($query) <
$r=@mysql_query($query);
if($err=mysql_errno())return $err;
if(@mysql_num_rows($r))
return mysql_fetch_array($r);
>

Here’s a quick way to duplicate or clone a record to the same table using only 4 lines of code:

// first, get the highest id number, so we can calc the new id number for the dupe
// second, get the original entity
// third, increment the dupe record id to 1 over the max
// finally insert the new record — voila — 4 lines!

$id_max = mysql_result(mysql_query(«SELECT MAX(id) FROM table_name»),0,0) or die(«Could not execute query»);
$entity = mysql_fetch_array(mysql_query(«SELECT * FROM table.» WHERE ),MYSQL_ASSOC) or die(«Could not select original record»); // MYSQL_ASSOC forces a purely associative array and blocks twin key dupes, vitally, it brings the keys out so they can be used in line 4
$entity[«id»]=$id_max+1;
mysql_query(«INSERT INTO it_pages («.implode(«, «,array_keys($Entity)).») VALUES (‘».implode(«‘, ‘»,array_values($Entity)).»‘)»);

Really struggled in cracking this nut — maybe there’s an easier way out there? Thanks to other posters for providing inspiration. Good luck — Tim

This is very useful when the following query is used:

`SHOW TABLE STATUS`

Different versions of MySQL give different responses to this.

Therefore, it is better to use mysql_fetch_array() because the numeric references given my mysql_fetch_row() give very different results.

If you use implode() with the return value by mysql_fetch_array, if you use MYSQL_BOTH on parameter 2, the result is not really what you’re expecting.
For example :
my sql database contains «Amine, Sarah, Mohamed»;

$array = mysql_fetch_array($resource,MYSQL_BOTH);
or $array = mysql_fetch_array($resource);
echo implode(» — «, $array);

the result is : Amine-Amine-Sarah-Sarah-Mohamed-Mohamed
and we expect just : Amine-Sarah-Mohamed

You must use MYSQL_NUM or MYSQL_ASSOC on parameter 2 to resolve the problem.

I never had so much trouble with null fields but it’s to my understanding that extract only works as expected when using an associative array only, which is the case with mysql_fetch_assoc() as used in the previous note.

However a mysql_fetch_array will return field values with both the numerical and associative keys, the numerical ones being those extract() can’t handle very well.
You can prevent that by calling mysql_fetch_array($result,MYSQL_ASSOC) which will return the same result as mysql_fetch_assoc and is extract() friendly.

I wrote some utility functions to improve usability and readability, and use them everywhere in my code. I suppose they can help.

function mysql_fetch_all($query,$MySQL=NULL) <
$r=@mysql_query($query,$MySQL);
if($err=mysql_errno($MySQL))return $err;
if(@mysql_num_rows($r))
while($row=mysql_fetch_array($r))$result[]=$row;
return $result;
>
function mysql_fetch_one($query,$MySQL=NULL) <
$r=@mysql_query($query,$MySQL);
if($err=mysql_errno($MySQL))return $err;
if(@mysql_num_rows($r))
return mysql_fetch_array($r);
>

Example use:
if(is_array($rows=mysql_fetch_all(«select * from sometable»,$MySQL))) <
//do something
>else <
if(!is_null($rows)) die(«Query failed!»);
>

If you think MySQL (or other) database
handling is difficult and requires lot’s of
code, I recommend that you try http://titaniclinux.net/daogen/

DaoGen is a program source code generator
that supports PHP and Java. It makes database
programming quick and easy. Generated sources
are released under GPL.

An example with mysql_fetch_array():

$result = mysql_query(«SELECT name FROM table WHERE/> $array = mysql_fetch_array($result);

array ([0] => «John», [‘name’] => «John»)

Then you can access to the results:

echo «The name is » . $array[0];
// or
echo «The name is » . $array[‘name’];

But the array is not referential. $array[0] is not a reference to $array[‘name’] or $array[‘name’] to $array[0], they are not relationed between. Because of that, the system will use excesive memory. With large columns, try to use mysql_fetch_assoc() or mysql_fetch_row() only.

If you perform a SELECT query which returns different columns with duplicate names, like this:

———
$sql_statement = «SELECT tbl1.colA, tbl2.colA FROM tbl1 LEFT JOIN tbl2 ON tbl1.colC = tbl2.colC»;

$result = mysql_query($sql_statement, $handle);

$row[0] is equivalent to $row[«colA»]

$row[1] is not equivalent to $row[«colA»].

Moral of the story: You must use the numerical index on the result row arrays if column names are not unique, even if they come from different tables within a JOIN. This would render mysql_fetch_assoc() useless.

[Ed. note — or you could do the usual ‘select tbl1.colA as somename, tbl2.colA as someothername. . .’ which would obviate the problem. — Torben]

Just thought I’d share these helper functions that I use to simplify processing of query results a bit:
// For a simple query that should return a single value, this returns just that value (or FALSE) so you can process it immediately
function db_result_single ( $result ) <
return ( $row = mysql_fetch_row ( $result )) && isset( $row [ 0 ]) ? $row [ 0 ] : false ;
>

// Returns the rows as an array of rows
// Providing a key_column gives you access to specific rows (e.g. if (isset($result_array[$user_id])) . )
function db_result_array ( $result , $key_column = null ) <
for ( $array = array(); $row = mysql_fetch_assoc ( $result ); isset( $row [ $key_column ]) ? $array [ $row [ $key_column ]] = $row : $array [] = $row );
return $array ;
>

// Returns an array of a single column of data that can optionally be keyed from second column (e.g. an array of user names keyed by user id)
function db_result_array_values ( $result ) <
for ( $array = array(); $row = mysql_fetch_row ( $result ); isset( $row [ 1 ]) ? $array [ $row [ 1 ]] = $row [ 0 ] : $array [] = $row [ 0 ]);
return $array ;
>
?>

Naturally, comments [to my email, not here] are welcome.

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.

Источник

Оцените статью