Hello. I am writing a script in php, which, at the user's request, displays a list of documents, 10 per page, everything is OK, everything works. But if you specify in the request what is not, it gives this error.

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given 

the very code of this type

 $query = "SELECT * FROM `nal` WHERE `name`LIKE \"%$search%\" AND `remainder` > 0 ORDER BY `id` DESC LIMIT $start_from, $on_page"; $res = mysql_query($query); while ($row = mysql_fetch_assoc($res)) { 

As I understand it, $ res returns the value False, and therefore further and the error gets out, how to fix it correctly. Add if before while? I tried to just write before this that if false to print echo, there are no results and exit, but he brought me both a message and an error.

Reported as a duplicate by Dmitriy Simushev , Mike , rjhdby , Denis Bubnov , Pavel Mayorov on Mar 14, 1717 at 14:29 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • what gives $ res if you write such code $ res = mysql_query ($ sql) or trigger_error (mysql_error (). "in". $ sql); - gudfar
  • most likely you have an error - gudfar

1 answer 1

Try the following code:

 $res = mysql_query($query); if (!$res) { echo "Не удается успешно выполнить запрос ($query). Ответ базы данных: " . mysql_error(); exit; } if (mysql_num_rows($res) == 0) { echo "Записи не найдены, просто выходим"; exit; } while ($row = mysql_fetch_assoc($res)) { 

In this case, you will see the reason why your code is not working.

  • issued Could not execute the query successfully (SELECT * FROM nal WHERE name LIKE "% ghjfgh%" AND remainder > 0 ORDER BY id DESC LIMIT -10, 10). Database response: You have an error in your SQL syntax; If I’m just going to print echo on this error, that there are no results, will this not have a great effect on the query? - Sergey
  • Well, here you have a syntax error, the first limit parameter is specified as -10, but this cannot be, make $ start_from a value of 0 or more and then the request will work - Yaroslav Molchan
  • You can tell more in what. Now my start is considered to be $ start_from = ($ current_page - 1) * $ on_page; that is, it receives data from a number (the current page is 1) * the number of records on the page, and if there is no result, then it turns out - 10, how is it better to stop the continuation? Just if you add that if -10, then do not perform further? - Sergey
  • I didn’t quite understand the essence, but I think yes, if less than 0 then everything is not necessary -10 maybe - Yaroslav Molchan
  • thanks a lot, it helped! - Sergey