gpt4 book ai didi

php - 在 session 中添加 ID?

转载 作者:行者123 更新时间:2023-11-29 05:05:53 24 4
gpt4 key购买 nike

我的登录和 session 正常,但我也希望能够调用用户名的 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);
}
?>

最佳答案

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

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

改变绑定(bind)结果。 BIND 结果是变量被赋值的地方。

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

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

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

关于php - 在 session 中添加 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48374324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com