Firstly, handling the errors during the development is very important so we check if our post are present, we check if we connected to the database, we check if our query passed and is OK to run, we check the parameters we are giving to the query and we finally execute the query.
After that you can use
bind_result to name a variable to receive the fields from your query, like I have done.
Notice how on my query I am using ? that is a prepared statement that we define using the
bind_param this is to avoid SQL injection, in your current code, SQL Injection is still possible since you're not sanitizing your variables.
Another mistake I believe you're doing is storing passwords as plain text that is VERY VERY WRONG, you should always encrypt the password to protect your users and yourself. That's why I do not include the password on my MySQL query, I first use only the user, if the user is found I then use the password he posted to match the retrieved password from the database, in this case I am using
bcrypt to do the task which is a very secure encryption library.
See here how to use
Only after I see that the password is valid I am then placing the data into the session and redirecting the user.
Besides all the errors I have pointed out at the bottom of my answer, here is how I would write your code.
die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
$sql = "SELECT Username, Password FROM `Members` WHERE Username = ?";
if (!$result = $con->prepare($sql))
die('Query failed: (' . $con->errno . ') ' . $con->error);
if (!$result->bind_param('s', $_POST['Username']))
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
die('Execute failed: (' . $result->errno . ') ' . $result->error);
if ($result->num_rows == 0)
die('No username found...');
$bcrypt = new Bcrypt(15);
if ($bcrypt->verify($password, $db_password))
$_SESSION['Username'] = $db_username;
echo 'Wrong Username or Password';
NOTE: The above code is merely an example and was not tested, if you notice any error with it let me know.
Some of the errors I have noticed on the code you have posted:
You're missing the closing
; over here:
$sql = "SELECT * FROM $Members WHERE Username = '$Username' and Password = '$Password'"
Also on your query you have
$Members but you have no
$Members variable defined anywhere in your code, did you perhaps meant to say
Members instead, as in:
$sql = "SELECT * FROM `Members` WHERE Username = '$Username' and Password = '$Password'";
$count = mysql_num_rows($result);
$count = mysqli_num_rows($result);‚ÄĆ
You have no query on the below part of the