gpt4 book ai didi

php - session 未与用户名 PHP 相关联

转载 作者:行者123 更新时间:2023-11-30 22:04:00 25 4
gpt4 key购买 nike

我不明白为什么我无法将登录的用户名与 session 相关联。如果你们能帮助我,我将非常感激?

示例代码如下:

session_start();

include 'includes/connect.php';

if (isset($_POST['user'], $_POST['pass'])) {
//assigning parameters to variables.
$user = $_POST['user'];
$pass = $_POST['pass'];

$sql = 'SELECT id FROM users WHERE username=(:user) AND password=(:pass)';

try {
$connect = new PDO("mysql:host=$host; dbname=$dbname;", $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$values = $connect->prepare($sql);
$values->bindParam('user', $user, PDO::PARAM_STR);
$values->bindParam('pass', $pass, PDO::PARAM_STR);
$values->execute();
$row_count = $values->rowCount();
$row = $values->fetch(PDO::FETCH_ASSOC);

////////////////////////////
//user and pass section [DB]
//$usr_db = $row['username'];
//$pwd_db = $row['password'];
////////////////////////////

if ($row_count === 1) {
$_SESSION['Logged_in'] = $user;
echo 'THIS TEXT REMAINS..';
}
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}

最佳答案

您还没有真正向我们提供足够的信息来帮助您,但我将做出有根据的猜测。您希望始终显示文本“THIS TEXT REMAINS..”。为什么这不会发生是因为除非在每个请求上发布用户名和密码,否则执行永远不会达到那个点,我认为这不会发生。如果您像这样重新组织代码,您可能会得到预期的结果。

session_start();

include 'includes/connect.php';

if (isset($_POST['user'], $_POST['pass'])) {
//assigning parameters to variables.
$user = $_POST['user'];
$pass = $_POST['pass'];

$sql = 'SELECT id FROM users WHERE username=(:user) AND password=(:pass)';

try {
$connect = new PDO("mysql:host=$host; dbname=$dbname;", $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$values = $connect->prepare($sql);
$values->bindParam('user', $user, PDO::PARAM_STR);
$values->bindParam('pass', $pass, PDO::PARAM_STR);
$values->execute();
$row_count = $values->rowCount();
$row = $values->fetch(PDO::FETCH_ASSOC);

////////////////////////////
//user and pass section [DB]
//$usr_db = $row['username'];
//$pwd_db = $row['password'];
////////////////////////////

if ($row_count === 1) {
$_SESSION['Logged_in'] = $user;
}
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}

// Moved the login check down here so it's executed on every request.
if (array_key_exists('Logged_in', $_SESSION) && $_SESSION['Logged_in'] !== null) {
echo 'THIS TEXT REMAINS..';
}

关于php - session 未与用户名 PHP 相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42363324/

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