首页 > 解决方案 > MySQL登录系统没有从数据库中获取结果

问题描述

<?php
session_start();
include 'dbh.inc.php'; //The connection ($conn) is working

$errors = array();  

    //Login
    if (isset($_POST['login'])) {
        $username = $_POST['username'];
        $password_1 = $_POST['password_1'];
    
        if (empty($username)) {
            array_push($errors, 'enter username');
        }
        if (empty($password_1)) {
            array_push($errors, 'enter password');
        }
        if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
            array_push($errors, 'username not correct');
            $username = "";
        }
    
        if (count($errors) == 0){      //The error is in this if condition
            $password = password_hash($password_1, PASSWORD_DEFAULT);
            $query = "SELECT * FROM users WHERE uidUsers=? AND pwdUsers=?";
            $stmt = mysqli_stmt_init($conn);
            mysqli_stmt_prepare($stmt, $query);
            mysqli_stmt_bind_param($stmt,'ss', $username, $password);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_store_result($stmt);
            $result = mysqli_stmt_num_rows($stmt);
            if (mysqli_num_rows($result) == 1){
                $_SESSION['uidUsers'] = $username;
                $idUsers_query = "SELECT idUsers FROM users WHERE uidUsers=? AND pwdUsers=?";
                $idUsers_stmt = mysqli_stmt_init($conn);
                mysqli_stmt_prepare($idUsers_stmt, $idUsers_query);
                mysqli_stmt_bind_param($idUsers_stmt,'ss', $username, $password);
                mysqli_stmt_execute($idUsers_stmt);
                mysqli_stmt_store_result($idUsers_stmt);
                $idUsers_result = $idUsers_stmt->get_result();
                $_SESSION['idUsers'] = $idUsers_result;
                $username = "";
                header("Location: https://...");
            }
            else{
                array_push($errors,'username or password not correct');
            }
        }
    }
    ?>

我的登录系统无法正常工作,因为我没有从我的数据库中获得结果或正确的结果。也许是因为数据库不接受“mysqli_stmt_store_result()”,但如果 mysqlnd 已打开,我无法查找(我的提供者无法更改它)。那么我的代码有错误还是数据库有问题?

标签: phpmysqlpassword-hash

解决方案


You shouldn't do this:

$password = password_hash($password_1, PASSWORD_DEFAULT);
$query = "SELECT * FROM users WHERE uidUsers=? AND pwdUsers=?";

password_hash() won't produce the same hash every time you run it.

You should run the query on the uid, retrieve the password, and use password_verify() on it.

I don't use mysqli so I'm not best placed on the various options with that. When you echo various debug points through the code, how far does it get?

You do seem to run the same query twice, and the first time you are using $idUsers_stmt when binding parameters despite it not existing at that point. That will stop things working, I would imagine, but you can debug that quite easily.


推荐阅读