抓取查询,放入 $_Session

Grab Query, drop in $_Session

试图获取我在最后为 $_SESSION 设置的值是来自查询的 user_id,而不是 $username。我似乎无法解决修改查询的问题。我敢肯定,对于这里的一些专家来说,这非常容易。

if(isset($_POST['login']))
{
    $username = mysqli_real_escape_string($conn,$_POST['username']);
    $pass = mysqli_real_escape_string($conn,$_POST['password']);
    $sel_user = "select user_id, user_first_name from users where username='$username' AND password='$pass'";
    $run_user = mysqli_query($conn, $sel_user);
    $check_user = mysqli_num_rows($run_user);

    if($check_user>0){
        $_SESSION['session_id']=$username;
    }
}

您需要从查询结果中读取行:

$row = mysqli_fetch_assoc($run_user);

然后你从那里得到 user_id

if ($row) {
    $_SESSION['session_id'] = $row['user_id'];
}

您无需致电 mysqli_num_rows()。如果没有匹配项,mysqli_fetch_assoc() 将 return false

请尝试以下代码段:

<?php

    if(isset($_POST['login']))
    {
        $username = mysqli_real_escape_string($conn, $_POST['username']);
        $password = mysqli_real_escape_string($conn, $_POST['password']);

        $selUserQuery = 'select user_id from users where username = "' . $username . '" and password = "' . $password . '"';

        if( $selUserStmt = mysqli_prepare($conn, $selUserQuery) )
        {
            mysqli_stmt_execute($selUserStmt);

            mysqli_stmt_bind_result($selUserStmt, $userId);

            while(mysqli_stmt_fetch($stmt))
            {
                $_SESSION['user_id'] = $userId;
            }
        }
    }

请注意,我已将您的 $_SESSION['session_id'] 更改为 $_SESSION['user_id'],希望能减少未来读者的困惑。