-2

I get this error when I try to do mysqli_num_rows()

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, bool given in C:\xampp\htdocs\php\search.php on line 13 There are no results matching your search

$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM posts WHERE a_title LIKE '%$search%' OR a_text LIKE '%$search%' OR a_author LIKE '%$search%' OR a_date LIKE '%$search%";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
Dharman
  • 30,962
  • 25
  • 85
  • 135
VilgotKH
  • 3
  • 5
  • http://php.net/manual/en/mysqli.query.php have a look on return values – Kurohige Dec 28 '18 at 18:01
  • 3
    Possible duplicate of [mysql\_fetch\_array()/mysql\_fetch\_assoc()/mysql\_fetch\_row()/mysql\_num\_rows etc... expects parameter 1 to be resource](https://stackoverflow.com/questions/2973202/mysql-fetch-array-mysql-fetch-assoc-mysql-fetch-row-mysql-num-rows-etc) – nofinator Dec 28 '18 at 18:01
  • Looks like your query is failing. You should add some proper error handling to see why. – Ivar Dec 28 '18 at 18:02
  • 2
    Note that mysqli_real_escape_string is not safe without setting the defualt charset it's in the [manual](http://php.net/manual/en/mysqli.real-escape-string.php) "Security: the default character set The character set must be set either at the server level, or with the API function mysqli_set_charset() " .. or using the better option prepared statements. – Raymond Nijland Dec 28 '18 at 18:06
  • Does this answer your question? [mysqli\_fetch\_assoc() expects parameter / Call to a member function bind\_param() errors. How to get the actual mysql error and fix it?](https://stackoverflow.com/questions/22662488/mysqli-fetch-assoc-expects-parameter-call-to-a-member-function-bind-param) – Dharman Oct 31 '19 at 21:43

1 Answers1

-1

It is very likey that your query has failed. In this case mysqli_query returns a boolean false value instead of a mysqli_result, as explained in the the manual.

You need to check for errors after running your query, like :

if ($result = mysqli_query($conn, $sql)) {
    $queryResult = mysqli_num_rows($result);
} else {
    printf("Error: %s\n", mysqli_error($conn));
}

By looking at your query I see that you are missing a final single quote ' (could be a typo as well) :

$sql = 
    "SELECT * 
     FROM posts 
     WHERE 
         a_title LIKE '%$search%' 
         OR a_text LIKE '%$search%'
         OR a_author LIKE '%$search%'
         OR a_date LIKE '%$search%";

To avoid that, and protect yourself against sql injection, you should use bind parameters.

GMB
  • 216,147
  • 25
  • 84
  • 135