准备会议声明

时间:2016-09-29 23:49:57

标签: php mysql mysqli

我最终决定开始使用预备语句。虽然,我是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();
            }

1 个答案:

答案 0 :(得分:2)

与上面的评论一样,在您使用->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组合。