首页 > 解决方案 > 使用简单的 PHP 登录用户但数据库查询失败

问题描述

我试图查询我的数据库以返回具有匹配 id 的用户,但似乎查询没有正确查询数据库,因为没有采取任何操作。该页面只是刷新而没有消息,并再次显示登录表单。我也尝试过使用 mysqli_fetch_array() 函数来返回数据库中的匹配行,但它也失败了。

       <?php

       if (isset ($_POST['username']) && (isset ($_POST['password']))){
       $username = $_POST['username'];
       $password = $_POST ['password'];

       //encrypting the password with md5 hashing
       $password_hash = md5($password);

       if (!empty ($username) && (!empty($password))) {


      $query= "SELECT id FROM users WHERE username = ‘$username' 
      AND password = '$password_hash' ";

        if ($query_run = mysqli_query ($mysql_conn, $query)) {
            $query_num_rows = mysqli_num_rows ($query_run);

            if ($query_num_rows == 0) { //checks to see if username and password exists in database
                echo 'Invalid username or password.';
            }
            else if ($query_num_rows == 1) {
                echo 'OK';
            }
        }
    }
    ?>
       <form action = "<?php echo $current_file; ?>" method = "POST">
       Username: <br>
       <input type = "textarea" name = "username"><br><br>
       Password: <br>
       <input type = "Password" name = "password"><br><br>
       <input type = "submit" value = "Log in">
       </form>

标签: phpsql

解决方案


我已经测试了以下,它工作正常。请注意,它只是检查用户名,如下所示。

 <?php

    //connect to the database - $mysql_conn as connection

    if (isset ($_POST['username']) && (isset ($_POST['password']))){
       $username = $_POST['username'];
       $password = $_POST ['password'];

        //encrypting the password with md5 hashing
        $password_hash = md5($password);

        if (!empty ($username) && (!empty($password))) {

            $query= "SELECT userID FROM crUsers WHERE userName = '$username';";

            //$query= "SELECT id FROM users WHERE username = '$username' AND password = '$password_hash';";
            $query= "SELECT id FROM users WHERE username = '$username';"; //Checking just username

            $query_run = mysqli_query ($mysql_conn, $query);
            $query_num_rows = mysqli_num_rows ($query_run);

            if ($query_num_rows == 0) { 
                echo 'Invalid username or password.';
            }
            else if ($query_num_rows == 1) {
               echo 'OK';
            }
            else {
               echo 'More than one user with these credentials';
            }
        }
    }
?>

<!DOCTYPE html>
<html lang="en-US" prefix="og: http://ogp.me/ns#">
<head>
    <meta charset="UTF-8" />
</head>

<body>

   <form method = "POST">
       Username: <br>
       <input type = "text" name = "username"><br><br>
       Password: <br>
       <input type = "Password" name = "password"><br><br>
       <input type = "submit" value = "Log in">
   </form>
</body>
</html>

推荐阅读