Reputation: 83
On my login page, if someone logs in with the correct detials they go to my main.php and if they don't have the correct details they should get shown an error message, but instead it goes to a blank screen!
Tried to figure this out for ages
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
session_start(); // Starting Session
include("connect.php");
$error=''; // Variable To Store Error Message
if (isset($_POST['login'])) {
$username = $_POST['username'];
if ($username == "") {
echo "Username field is empty!";
header("Location: incorrectlogin.php");
}else{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($con,$username);
$password = mysqli_real_escape_string($con,$password);
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "root", "", "game");
// Selecting Database
$db = mysqli_select_db($con,"game");
$query = mysqli_query($con,"select * from users where password='$password' AND username='$username'");
$rows = mysqli_num_rows($query) or die(mysqli_error($con));
if ($rows == 1) {
$_SESSION['login_user']=$username;
header("location: main.php");
} else {
echo "That username or password is incorrect";
$error = "Username or Password is invalid";
}
}
}
It might just be me but it looks like it SHOULD work, any ideas?
Upvotes: 1
Views: 130
Reputation: 270609
The problem resides here in the error handling (ironically) added to mysqli_num_rows()
:
$rows = mysqli_num_rows($query) or die(mysqli_error($con));
When mysqli_num_rows()
returns 0
(no rows found), the or die()
is triggered here. Since there was no error, you get no output from mysqli_error()
.
But zero rows returned is not an error state so it is not appropriate to add error handling to it. You are already handling the row count returned subsequently with:
if ($rows == 1) {
// etc...
}
...so you can safely remove the or die(...)
. It would be more appropriate to use that error handling expression on the previous call to mysqli_query()
, where an error can actually occur if the SQL string is invalid.
I also would be remiss if I didn't mention the issue of storing user passwords in plain text, as this implies:
$password = mysqli_real_escape_string($con,$password);
I recommend reviewing How do you use bcrypt for hashing passwords in PHP for truly excellent examples on how to improve the security of your password storage.
Upvotes: 2
Reputation: 69
I think you are missing if
statement , can u paste the whole code (or) few lines above and below of the above line s of code
Upvotes: 0