Question

I am fairly new to PHP. I have been trying to work this issue out but with no luck. Hoping for some help from you guys!

So it's fairly simple. I have a form that is running a PHP script to check if the user exists in MySQL database. When users are created I am hashing the password with sha1 (something I am new to). The hashing works just fine. But when I then try to check user on the form, it keeps returning false.

The code checking if user exists (user_login.php)

<?php
//include db connect
  include ("db_con.php");

//set variable names
  $username = $_POST['username'];
  $password = $_POST['password'];

//start session
  session_start();

 $checklogin = mysqli_query($con, "SELECT * FROM users WHERE username = '".$username."' AND password= sha1('".$password."')"); 
  if(mysql_num_rows($checklogin) == 1) {  
   echo 'Success!';
 } else {
  echo 'No';
 }

?>

If needed here is the form (login_form.php)

<table border="1">
          <form action="functions/user_login.php" name="login" method="post">
            <tr>
              <td><input type="text" name="username" placeholder="Enter Username" required /></td>
            </tr>
            <tr>
              <td><input type="password" name="password" placeholder="Enter Password" required  /></td>
            </tr>
            <tr>
              <td><input type="submit" value="Login" /></td>
            </tr>
          </form>
        </table>

If I run echo sha1($password); it does properly echo the same hashed password that is stored in the database. However, when I run it with the mysql_num_rows code it keeps returning "No.' Hopefully the info given is enough for someone to see where my issue lies. If not please let me know what else I can include.

Was it helpful?

Solution

Just change this:

$checklogin = mysqli_query($con, "SELECT * FROM users WHERE username = '".$username."' AND password= sha1('".$password."')"); 
 if(mysql_num_rows($checklogin) == 1) {  //Wrong line
  echo 'Success!';
 } else {
 echo 'No';
 }

To this:

 $checklogin = mysqli_query($con, "SELECT * FROM users WHERE username = '".$username."' AND password= sha1('".$password."')"); 
 if(mysqli_num_rows($checklogin) == 1) {  //mysqli
  echo 'Success!';
 } else {
 echo 'No';
 }

OTHER TIPS

<?php
//include db connect
  include ("db_con.php");

//set variable names
  $username = htmlspecialchars($_POST['username']);
  $password = htmlspecialchars($_POST['password']);

//start session
  session_start();

 $checklogin = mysqli_query($con, "SELECT * FROM users WHERE username = '".$username."' AND password= sha1('".$password."')"); 
  if(mysqli_num_rows($checklogin) == 1) {  
   echo 'Success!';
 } else {
  echo 'No';
 }

?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top