Reputation: 218
I am having this code:
$sql=mysqli_query($con,"SELECT username, password, email FROM users WHERE username=$username");
if(mysqli_num_rows($sql)>=1)
{
echo "<div class='form'>
<h3>Username already in use.</h3></div>";
}
When using this code, it returns the following warning:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in...
Why it showing this warning and how do I fix it?
Upvotes: 1
Views: 133
Reputation: 157895
The way you are running your query is wrong. It's error prone and will always give you errors like that. Moreover, it is prone to SQL injection as well.
When you are adding a variable directly into the query, its contents could interfere, which will result in many troubles, from the error like this to SQL injection. To get rid of such errors once for all you must prepare your query first, adding a question mark in place of a variable, and then send it separately. This way it will never interfere.
You must prepare your query first, then bind a variable, and then execute:
$sql = "SELECT username, password, email FROM users WHERE username=?";
$stmt = $con->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$res = $stmt->get_result();
if($res->num_rows())
{
echo "<div class='form'>
<h3>Username already in use.</h3></div>";
}
Upvotes: 2
Reputation: 1990
If you look at the documentation for the mysqli_query
method, you'll see that when the query fails, the method returns False
. This is what's happening in your example. You are then passing that boolean into mysqli_num_rows
which explains the error message.
To solve this, you need to do some error checking. At the very least, check to see if mysqli_query
returned False
before moving on to the rest of your code.
If you're doing anything more than just experimenting on your local machine, it is probably best to do what Your Common Sense suggests in his answer, and used prepared statements.
Upvotes: -1