我正在将旧的 mysql 转换为 PDO,我遇到了第一个问题。
我想根据$_SESSION['user_id']
但未分配数据库中的 user_id 来回显用户信息,$_SESSION['user_id']
因此我进入Notice: Undefined index: user_id in
帐户页面$user_id = $_SESSION['user_id'];
并print_r($_SESSION['user_id']);
在线。
我确实session_start();
在页面顶部。
班级
class User {
public $user_id = null;
public function userInfo($user_id) {
global $db;
$query = $db->prepare("SELECT user_id, username, email FROM users WHERE user_id = :id");
$query->bindValue(':id', $user_id);
$query->execute();
return $query->fetch();
}
public function login($login, $password){
global $db;
$query = $db->prepare("SELECT COUNT(user_id) as count, user_id FROM users WHERE username = :user AND password = :pass");
$query->bindValue(':user', $login);
$query->bindValue(':pass', $password);
$query->execute();
$result = $query->fetchColumn();
if ($result) {
$this->user_id = $result['user_id'];
}
return $result;
}
}
登录
if (isset($_POST['login'], $_POST['password'])) {
$login = $_POST['login'];
$password = sha1($_POST['password']);
$errors = array();
if (empty($login) || empty($password))
{
$errors[] = 'All fields required!';
}
else {
$user = new User;
$log_in = $user->login($login, $password);
if($log_in) {
$_SESSION['user_id'] = $user->user_id;
header('Location: account.php');
exit();
} else {
$errors[] = 'Username or password incorrect!';
}
}
if (!empty($errors)){
foreach ($errors as $error)
{
echo '<div id="error"><strong>', $error, '</strong></div><br />';
}
}
}
账户页面
$user = new User;
$user_id = $_SESSION['user_id'];
$data = $user->userInfo($user_id);
echo $data['username'],'<br />';
echo $data['email'],'<br />';
echo '<pre>';
print_r($_SESSION['user_id']);
echo '</pre>';
if(isset($_SESSION['user_id'])){
echo '<pre>';
print_r($data);
echo '</pre>';
echo $data['username'],'<br />';
echo $data['email'],'<br />';
}else {
echo 'Please log in!';
}