Reputation: 13
First the code
mysqli_free_result($wynik);
$query = mysqli_query($dbcon, "SELECT * FROM user WHERE login = '$login' AND password ='$pass'");
$sql = mysqli_num_rows($query)
or die(drop dead);
echo $sql;
if ($sql > 0) {
$_SESSION['user'] = $login;
$_SESSION['auth'] = TRUE;
echo $login;
I have a small issue with this code. When $query finds a result everything works fine, but when it returns no results $sql part dies. I can't understand why. When i run the query in database it works fine and returns 0 results.
Upvotes: 0
Views: 279
Reputation: 6507
or die()
isn't some special error-handing feature of PHP. It actually performs a logical OR on the left and right values. It's commonly used to handle errors with functions that return a 0
on error because it's a short circuit operator. That means that it only evaluates the second operand if the first one is not a "True" value ( see How does true/false work in PHP? for info on how true/false is handled in PHP).
What's happening here is $sql = sqli_num_rows($query) or die()
is the same as $sql = 0 or die()
. Since 0 is a false value, it tries to evaluate the die()
and dies.
Upvotes: 0
Reputation: 26450
Because when you get no rows, you basically get 0 or die()
. 0 is "falsy", so your die is executed. You don't want a die()
there, basically just remove it.
$sql = mysqli_num_rows($query); // Don't use die() for this
See this live demo.
It's more common to use or die()
after the query, although it's not the best handling of errors, this is probably where you've seen it before
$query = mysqli_query($dbcon, "SELECT * FROM user WHERE login = '$login' AND password ='$pass'") or die ("Query failed ".mysqli_error($dbcon));
Also you should look into prepared statements to protect your database against SQL injection. See the links given below.
Upvotes: 3