Solving PHP Warning mysqli_num_rows() expects, boolean given

Started on the old forum in January 2013 · view the original in the archive · old links redirect here

No replies · 1,123 views · started 13 years ago · 1 min read

arnage Lead · 811 posts #1

Well, here it is, usually problematic part of code is like:

$query = mysqli_query($conn, 'SELECT COUNT(`id`) FROM `table` WHERE `id` = '.$id.'');
	$count = mysqli_num_rows($query);

... which is throwing error:

PHP Warning:  mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /www/user/public_html/index.php on line 2

... so the query must be in if():

if ($query = mysqli_query($conn, 'SELECT COUNT(`id`) FROM `table` WHERE `id` = '.$id.'')) {
	$count = mysqli_num_rows($query);
}

But this is throwing this error:

PHP Notice:  Undefined variable: count in /www/user/public_html/index.php on line 2

... so simple define it:

// if you want integer:
$count = (int)''; // perfectly valid way
// if you want string:
$count = '';
// or use settype(): http://php.net/manual/en/function.settype.php
settype($count, 'int');
if ($query = mysqli_query($conn, 'SELECT COUNT(`id`) FROM `table` WHERE `id` = '.$id.'')) {
	$count = mysqli_num_rows($query);
}

And there will be no Warning nor Notice. 🙂

<!DOCTYPE html PUBLIC "-//***WAPFORUM**.**RS***

Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close