ProgrammingHelp1 ProgrammingHelp1 - 4 months ago 9
PHP Question

login system not working correctly

I enter the correct password and username exactly how it is like in my database, but it says it is invalid. I then tried to enter the username and password incorrectly and was meant to echo the same error as it did.

below is my code:

<?php
$servername = "localhost";
$dbname = "dbtechnerdzzz";
$user = "root";
$password = "root";
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['form-username']) || empty($_POST['form-password'])) {
$error = "Username or Password is invalid";
}
else
{
$connection=mysqli_connect($servername, $user, $password, $dbname);
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// To protect MySQL injection for Security purpose
$username = mysqli_real_escape_string($connection,$_POST['form-username']);
$password = mysqli_real_escape_string($connection,$_POST['form-password']);

// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query($connection,"select * from accounts where Password='$password' AND Username='$username'");
if(!$query) die(mysqli_error($connection));
$rows = mysqli_num_rows($query);
echo mysqli_error ( $connection );
if ($rows == 0) {
// zero row found

$error = "Username or Password is invalid";
//header("location: signin.php"); // Redirecting To login Page
echo "Username or Password is invalid";

} else {
// at least one row has been found

$_SESSION['login_user'] = $username; // Initializing Session
header("location: profile.php"); // Redirecting To profile Page
echo "login successful"; // this line will never be executed because user is redirected with header (line above)

}

mysqli_close($connection); // Closing Connection
?>


Update 1 (21 July 2016 00:27 BST):

I got this error in the browser:


The localhost page isn’t working localhost is currently unable to
handle this request. HTTP ERROR 500


I then looked in my logs and it said:


PHP Parse error: syntax error, unexpected end of file on line 44


line 44 is:

?>


so it's the end of the file.

Answer

If I were you I would do the if statement this way :

if ($rows == 0) {
  // zero row found

  $error = "Username or Password is invalid";
  //header("location: signin.php"); // Redirecting To login Page
  echo "Username or Password is invalid";

} else {
  // at least one row has been found

  $_SESSION['login_user'] = $username; // Initializing Session
  header("location: profile.php"); // Redirecting To profile Page
  echo "login successful"; // this line will never be executed because user is redirected with header (line above)

}

mysqli_close($connection); // Closing Connection

If you happen to have two rows with the same user, the if statement will still work and echo "login successful"

Comments