0

I am currently developing a hotel reservation system. I've created a sign up and login page for the guest to make reservation. Ive tested my program and whenever I enter details for sign up process, it got successfully stored in the database. The problem now is that when I try to enter the same detail for login process, its not working. I feel like its not connected to the database but I don't know what I got wrong. The error that I get everytime I try to login is "incorrect id or password", eventhough Ive already stored the same details in database during signup process.

Please help me find the solution for this one. Below are my coding so far. Thank you.

*note: This project is done during online class so my groupmate and I have to do our parts and I am in charge of putting in all together. This part is my friend's. When she runs it on her computer, she can login successfully. I have already changed the database name to mine but its still seems like its not connected for some reason :/

<?php

    $hostname = "localhost";
    $username= "root";
    $password = "";
    $db_name = "project";

    $connect = mysqli_connect($hostname, $username, $password, $db_name);

                
    if (!$connect){
        echo "Connection failed!";
    }

?>

This is the login page. (File Name: custlogin.php)

<!DOCTYPE html>
<html lang="en">
     <head>
          <meta charset = "UTF-8">
          <title> My First Web Page </title>
     </head>
     
<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
    body 
    {
        font-family: Arial, Helvetica, sans-serif;
        font-size: 15px;
        background-attachment: fixed;
        background-size: 100% 100%;
        margin: 0;
        padding: 0;
        background-image: url('https://assets.hyatt.com/content/dam/hyatt/hyattdam/images/2019/06/25/1437/Grand-Hyatt-Seoul-P1448-Sofabed-Service.jpg/Grand-Hyatt-Seoul-P1448-Sofabed-Service.16x9.jpg?imwidth=1280');
        background-repeat: no-repeat;
    
    }

    
    input[type=text], input[type=password] 
    {
       width: 40%;
       padding: 12px 20px;
       margin: 8px 0;
       border: 2px solid #ccc;
       box-sizing: border-box;
    }

    button 
    {
       background-color: black;
       color: white;
       font-family: 'Poppins', sans-serif;
       font-size: 13px;
       border: none;
       cursor: pointer;
       text-align : center;
       width: 70px;
       height:30px;
    }

    button: hover 
    {
       opacity: 0.8;
    }

    .cancelbtn, .join 
    {
      width: 70px;
      height:30px;
      text-align: center;
      background-color: black;
      color:white;
    }

    .container
    {
      margin-top: 110px;
      padding: 30px;
      background-color: white;
      margin-left: 300px;
      margin-right: 300px;
      text-align:center;
      background: rgba(211,211,211,0.6);

    }

    span. password
    {
      float: right;
      padding-top: 16px;
    }

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
  span.password {
     display: block;
     float: none;
  }
  .cancelbtn {
     width: 100%;
  }

* {
  box-sizing: border-box;
}

/* Create two equal columns that floats next to each other */
.column {
  float: left;
  width: 70%;
  padding: 10px;

}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

</style>
<body>

  <div class="container">
    <form action = "custlogin2.php" method="post">
    <?php if (isset($_GET['error'])) { ?>
            <p class="error"><?php echo $_GET['error']; ?></p>
    <?php } ?>
    
    <p style="text-decoration: underline;"><b>WELCOME TO SECRET MIRAGE HOTEL</b></p><br><br><br>
    

    <b>Member Id</b><br>
    <input type="text" placeholder="Enter Member Id" name="memberID" required><br>

    <b>Password</b><br>
    <input type="password" placeholder="Enter Password" name="password" required><br><br>
    
     
    <br>

    <button type="submit">Sign In</button>
     
   </form> <br>
   <button onclick="document.location='custsignup.php'" class="join" style="float:left; width: 90px;">Join Now</button>
   <button onclick="document.location='project.php'" class="cancelbtn" style="float:right;">Cancel</button>
   <br>
  </div>



</body>
</html>

This one to check. (custlogin2.php)

<?php 
session_start(); 
include "db_connect.php";

if (isset($_POST['memberID']) && isset($_POST['password'])) {

    function validate($data){
       $data = trim($data);
       $data = stripslashes($data);
       $data = htmlspecialchars($data);
       return $data;
    }

    $memberID = validate($_POST['memberID']);
    $password = validate($_POST['password']);

    
        // hashing the password
        $password = md5($password);

        
        $sql = "SELECT * FROM customer WHERE memberID='$memberID' AND password='$password'";

        $result = mysqli_query($connect, $sql);

        if (mysqli_num_rows($result) === 1) {
            $row = mysqli_fetch_assoc($result);
            if ($row['memberID'] === $memberID && $row['password'] === $password) {
                $_SESSION['memberID'] = $row['memberID'];
                $_SESSION['firstName'] = $row['firstName'];
                $_SESSION['lastName'] = $row['lastName'];
                $_SESSION['cust_email'] = $row['cust_email'];
                $_SESSION['cust_Address'] = $row['cust_Address'];
                header("Location: home2.php");
                exit();
            }else{
                header("Location: custlogin.php?error=Incorect Id or Password");
                exit();
            }
        }else{
            header("Location: custlogin.php?error=Incorect Id or Password");
            exit();
        }
    
    
}else{
    header("Location: custlogin.php");
    exit();
}

?>

This the sign up form

<body>
<div class="container">
<form action="custsignup-check.php" method="post">

<?php if (isset($_GET['error'])) { ?>
            <p class="error"><?php echo $_GET['error']; ?></p>
<?php } ?>

<?php if (isset($_GET['success'])) { ?>
            <p class="success"><?php echo $_GET['success']; ?></p>
<?php } ?>

<div class="row">
<p style="font-size:18px; text-decoration:underline;"><b>Join Secret Mirage</b></p>
  <div class="column">
 
    <b>First Name</b><br>  
             <input type="text" 
             placeholder="Enter First Name" 
             name="firstName" required><br>
          
          
    <b>Id Number</b><br>
             <input type="text" 
             placeholder="Enter Id Number" 
             name="memberID" required><br>
            
    
    <b>Password</b><br>
             <input type="password" 
             placeholder="Enter Password" 
             name="password" required><br>
            
          
    <b>Email</b><br>
             <input type="text"
             placeholder="Enter Email" 
             name="cust_email" required><br>
            
    
  </div>
  <div class="column">
  
    <b>Last Name</b><br>
             <input type="text" 
             placeholder="Enter Last Name" 
             name="lastName" required><br>
             
          
    <b>Address</b><br>'
             <input type="text" 
             placeholder="Enter Address"
             name="cust_Address" required><br>
            
          
          
    <b>Confirm Password</b><br>
    <input type="password" placeholder="Confirm Password" name="re_password" required><br>
    
    <p style="text-align:justify;">By signing up, I agree to Secret Mariage's Terms of Use and Secret Mariage Member
    Terms and Conditions.<p>
  </div>

  
</div>
<button type="submit">Join</button>

</form>

<button onclick="document.location='project.php'" class="cancelbtn">Cancel</button> 
<button onclick="document.location='custlogin.php'" class="login">Login</button> 
<br>
</div>


</body>
</html>

This is the sign up check.

<?php 
session_start(); 
include "db_connect.php";

if (isset($_POST['memberID']) && isset($_POST['firstName'])
    && isset($_POST['lastName']) && isset($_POST['password']) 
    && isset($_POST['cust_email']) && isset($_POST['cust_Address'])) {

    function validate($data){
       $data = trim($data);
       $data = stripslashes($data);
       $data = htmlspecialchars($data);
       return $data;
    }

    $memberID = validate($_POST['memberID']);
    $firstName = validate($_POST['firstName']);
    $lastName = validate($_POST['lastName']);
    $password = validate($_POST['password']);
    $re_password = validate($_POST['re_password']);
    
    $cust_email = ($_POST['cust_email']);
    $cust_Address = ($_POST['cust_Address']);

    if($password !== $re_password){
        header("Location: custsignup.php?error=The confirmation password  does not match");
        exit();
    }

    else{

        // hashing the password
        $password = md5($password);

        
           $sql2 = "INSERT INTO customer(memberID, firstName, lastName, password, cust_email, cust_Address) VALUES('$memberID', '$firstName', '$lastName','$password', '$cust_email', '$cust_Address' )";
           $result2 = mysqli_query($connect, $sql2);
           if ($result2) 
           {
             header("Location: custsignup.php?success=Your account has been created successfully");
             exit();
           }
           else
           {
                header("Location: custsignup.php?error=unknown error occurred");
                exit();
           }
        
    }
    
}else
{
    header("Location: custsignup.php");
    exit();
}
  • 2
    "It's not working" is not really explicit. What error do you get ? – Reqven Jan 09 '21 at 14:16
  • it will show "incorrect id or password" – Azariah Natasha Jan 09 '21 at 14:21
  • 3
    `md5` ... from [the manual](https://www.php.net/manual/en/function.md5.php): "_Warning: It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See the [Password Hashing FAQ](https://www.php.net/manual/en/faq.passwords.php#faq.passwords.fasthash) for details and best practices._" – brombeer Jan 09 '21 at 14:25
  • 3
    this code is **vulnerable** to **sql injection** so use only **prepared stements with parameters** see https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php further mds is not secure use the built in hashing function form this – nbk Jan 09 '21 at 14:25
  • 1
    Dump your `$sql` variable before executing the request to see what's wrong. – Reqven Jan 09 '21 at 14:27
  • it still shows the same error :/ – Azariah Natasha Jan 09 '21 at 14:32
  • 1
    What error do you get? Please include it in your question. I'd also suggest you look into prepared statements. – Bastiaan Buitelaar Jan 09 '21 at 14:36
  • I am very sorry for asking, but I am new so may I know what you mean by prepared statements? – Azariah Natasha Jan 09 '21 at 14:41
  • Have a look here: https://www.w3schools.com/php/php_mysql_prepared_statements.asp. The essence is that you don't put data directly in the query, which makes it safer. – Bastiaan Buitelaar Jan 09 '21 at 14:56

2 Answers2

0

Tips for solving your issue:

  • Add an error_log(print_r($sql,true)); to your code after you have called the $sql variable. copy this SQL and run it in your MySQL directly and see if it generates any result.

    • If it does generate a reesult then the issue is in your PHP.
    • If it does not generate a result then the issue is in the data in your MySQL.
  • Do not run validate on your $password string.

  • Add an error_log(print_r($row,true)); to your code after you have loaded the row data and see if it shows anything?

  • Be careful with type checking comparison === . If your memberId is an integer value, you should ensure that both side of the check are the correct type.

      `if((int)$row['memberID'] === (int)$memberID 
          && (string)$row['password'] === (string)$password){...`
    

Advice for your MySQL

  • You should NOT be using root as your active username, root is too open and is a huge security risk. You need to make a new SQL user associated with this database and use that connection rather than root.

  • You should be setting your Connection Character Set when you establish your MySQL script connection.

  • SELECT * is bad practise and inefficient. You should select only the columns you are actually going to use.

  • mysqli_num_rows (and all similar PHP processes) are unreliable and can in certain situations be inaccurate. If you want a row count you should run an SQL SELECT COUNT(*)... query. You don't need to count rows here, simply you need to be sure that the array that is generated is populated so you can simply use if(count($result) > 0){... instead.

Advice for your PHP coding style:

How to learn more about how to code in PHP correctly and safely:

Advice for your HTML

  • You should be using HTML5. You should stop using older HTML4 tags and reshape your HTML pages to use HTML syntax (<strong> instead of <b>, etc.)

  • If you insist on using <style> syntax, it should be inside your <head> element. But using this is NOT RECOMMENDED.

Advice for your CSS

  • You should NOT be using inline CSS. You should be putting your CSS styles in an external stylesheet and calling that stylesheet in the <head> part of your HTML page.

  • It is bad practise to use float: for block positioning, there are many better methods of placing elements on the page with CSS3 such as Flexbox and others.

What you've done right:

  • You have correctly put exit statements after header redirects. Many people fail to do this, so I'm pleased to see you have this sorted! :-)
Martin
  • 22,212
  • 11
  • 70
  • 132
  • Thank you so much for your tips and advice. I will try to follow and apply them and hopefully, it will help me figure things out. – Azariah Natasha Jan 09 '21 at 19:14
  • @AzariahNatasha please see my update to my tips. thanks. – Martin Jan 09 '21 at 19:23
  • I'm really sorry but may I ask you a question? This part of our project was done by my friend so those codes are hers. I am in charge of putting things together to complete our website. When she tested it, its working just fine but when she gave the file to me, it suddenly won't function right eventhough Ive already change the database name and other things related. I want to know what could be the reason. thank you – Azariah Natasha Jan 09 '21 at 19:37
  • @AzariahNatasha you need to view your error logs to see what errors are reported. – Martin Jan 09 '21 at 19:42
-1

I am going to try to give you a simple solution and at the same time protect yourself from sql injection:

First here is the code of the connection to the database, file called connection.php

<?php

function connect(){
$con=mysqli_connect("localhost","root","","dbname");
if(!$con)
die("Could not connect");

return $con;
}
?>

Now the php code or form used to login:

login.php:

<html>
<head><title>Login Page</title></head>
<body>
<form method="POST" action="checkLogin.php">
<label>Username:
<input type="text" name="username" required>
</label><br>

<label>Password
<input type="password" name="password" required>
</label><br>

<input type="submit" value="Login">
</form>
</body>
</html>

Now I am going to define a function in another file called validate.php

<?php
    function validate($con,$data){
    $newData=htmlspecialchars($data);
    $newData=mysqli_real_escape_string($con,$newData);//this function is a built in function used to protect you from sql injection. It requires 2 parameters.
The first one is the connection to database and the second is the variable you are using

return $newData;
    }
?>

Now the php code used to check if the username and password are right . the file is called checkLogin.php:

    <?php
    session_start();
    require("connection.php");
    require("validate.php");
    
    $username=$_POST["username"];
    $password=$_POST["password"];
    
$con=connect();//this function is called from the connection.php file

    $username=validate($con,$username);//this function called from validate.php file
    $password=validate($con,$password);
    
    $checkLogin="SELECT count(*) from users where username='$username' and password='$password'";

    
    $res=mysqli_query($con,$checkLogin);
    $row=mysqli_fetch_array($res);
    
    if($row[0]==1){
    $_SESSION["username"]=$username;
    mysqli_close($con);
    header("Location:home.php");
    exit();
    }else{
    header("Refresh:0 ; url=login.php");//this wait until the alert shows up and when you press ok in the alert it will take you back to the login page
    echo "<script>";
    echo "window.alert('Wrong username and password')";//you can write javascript inside php
    echo "</script>";
    }
    mysqli_close($con);
    ?>
Charbelalam
  • 104
  • 7