我不明白为什么我无法将登录的用户名与会话相关联。 如果你能帮助我,我会非常感激吗?
以下是示例代码:
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();
}
}
答案 0 :(得分:0)
您还没有给我们足够的信息来帮助您,但我会做出有根据的猜测。你想要文本"这个文字仍然存在。"一直出现。为什么这不会发生是因为除非在每个请求上发布用户名和密码,否则执行永远不会到达那一点,我认为这不是发生的事情。如果您重新组织这样的代码,您可能会得到您期望的结果。
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..';
}