mysql_num_rows返回false

时间:2014-03-03 20:03:46

标签: php mysql

我对PHP很新。我一直试图解决这个问题,但没有运气。希望得到你们的帮助!

所以这很简单。我有一个运行PHP脚本的表单来检查用户是否存在于MySQL数据库中。创建用户时,我使用sha1(我不熟悉的东西)对密码进行哈希处理。哈希工作得很好。但是当我尝试在表单上检查用户时,它会一直返回false。

检查用户是否存在的代码(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';
 }

?>

如果需要,表格(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>

如果我运行echo sha1($password);,它会正确回显存储在数据库中的相同哈希密码。但是,当我使用mysql_num_rows代码运行它时,它会一直返回“否”。希望所提供的信息足以让人知道我的问题所在。如果不是,请告诉我我还能包括哪些内容。

2 个答案:

答案 0 :(得分:2)

只需改变一下:

$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';
 }

对此:

 $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';
 }

答案 1 :(得分:1)

<?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';
 }

?>