我终于决定开始使用准备好的语句。虽然,我对正确与否的判断是50/50。我正在尝试使用准备好的语句创建登录页面。不过,似乎除了用户名$_SESSION
之外,它没有检索任何会话值。
这是我的代码:
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql = "SELECT * FROM users WHERE BINARY username=? AND BINARY password=?";
if($stmt = $db->prepare($sql)){
$stmt->bind_param("ss",$username,$password);
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
if($num_rows >= 1){
$_SESSION['loggedin'] = $username;
$_SESSION['country'] = $num_rows['country'];
$_SESSION['email'] = $num_rows['email'];
$_SESSION['avatar'] = $num_rows['u_avatar'];
$_SESSION['is_gm'] = $num_rows['is_gm'];
$_SESSION['user_lvl'] = $num_rows['user_lvl'];
$_SESSION['totalposts'] = $num_rows['post_total'];
$_SESSION['totalcoins'] = $num_rows['coins_total'];
$_SESSION['totalvotes'] = $num_rows['vote_total'];
$_SESSION['secquest'] = $num_rows['sec_quest'];
$_SESSION['secanswer'] = $num_rows['sec_answer'];
$_SESSION['join_date'] = $num_rows['join_date'];
header("Location: /index.php");
exit();
} else {
echo "<p class='error_msg'>No accounts could be found with the given credentials.</p>";
}
$stmt->free_result();
$stmt->close();
$db->close();
}
最佳答案
就像上面的注释一样,在使用->get_result()
之后,该获取以下内容了:
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
if($num_rows >= 1) {
$row = $result->fetch_assoc(); // fetch it first
$_SESSION['loggedin'] = $username;
$_SESSION['country'] = $row['country'];
$_SESSION['email'] = $row['email'];
$_SESSION['avatar'] = $row['u_avatar'];
$_SESSION['is_gm'] = $row['is_gm'];
$_SESSION['user_lvl'] = $row['user_lvl'];
$_SESSION['totalposts'] = $row['post_total'];
$_SESSION['totalcoins'] = $row['coins_total'];
$_SESSION['totalvotes'] = $row['vote_total'];
$_SESSION['secquest'] = $row['sec_quest'];
$_SESSION['secanswer'] = $row['sec_answer'];
$_SESSION['join_date'] = $row['join_date'];
header('Location: /index.php');
exit();
}
使用
$num_rows['join_date']
没有任何意义,因为您已经知道这会产生实际的行数,它不包含所需的值。您已经检查了它是否包含数字if($num_rows >= 1) {
旁注:是时候放弃
md5
并开始使用password_hash
+ password_verify
组合了。关于php - session 准备声明,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39781691/