在会话中添加ID?

时间:2018-01-22 03:29:37

标签: php mysql login

我的登录和会话工作正常,但是我也希望能够调用用户名的ID,但我不知道如何做到这一点。任何帮助都会很棒!

所以,我正在尝试添加$_SESSION['id'] = $id;,但我不确定要添加什么。

<?php
require_once 'config.php';

$username = $password = "";
$username_err = $password_err = "";


if($_SERVER["REQUEST_METHOD"] == "POST"){



if(empty(trim($_POST["username"]))){
    $username_err = 'Please enter username.';
} else{
    $username = trim($_POST["username"]);
}


    $password_err = 'Please enter your password.';
} else{
if(empty(trim($_POST['password']))){
    $password = trim($_POST['password']);
}


if(empty($username_err) && empty($password_err)){

    $sql = "SELECT username, password FROM users WHERE username = ?";

    if($stmt = mysqli_prepare($link, $sql)){

        mysqli_stmt_bind_param($stmt, "s", $param_username);


        $param_username = $username;


        if(mysqli_stmt_execute($stmt)){

            mysqli_stmt_store_result($stmt);


            if(mysqli_stmt_num_rows($stmt) == 1){                    

                mysqli_stmt_bind_result($stmt, $username, $hashed_password);
                if(mysqli_stmt_fetch($stmt)){
                    if(password_verify($password, $hashed_password)){

                        session_start();
                        $_SESSION['username'] = $username;      
                        header("location:app.php");
                    } else{

                        $password_err = 'The password you entered was not valid.';
                    }
                }
            } else{

                $username_err = 'No account found with that username.';
            }
        } else{
            echo "Oops! Something went wrong. Please try again later.";
        }
    }


    mysqli_stmt_close($stmt);
}


mysqli_close($link);
}
?>

1 个答案:

答案 0 :(得分:3)

假设您有ID列,请将ID添加到查询中。您需要这个来从数据库中获取ID。

$sql = "SELECT username, password, id FROM users WHERE username = ?";

更改绑定结果。 BIND结果是赋值变量的地方。

mysqli_stmt_bind_result($stmt, $username, $hashed_password, $id);

然后在密码验证部分获取ID:

session_start();
$_SESSION['username'] = $username;   
$_SESSION['id'] = $id; 
header("location:app.php");