使用mysqli_stmt_bind_result将会话值设置为数据库值

时间:2018-04-16 19:59:22

标签: php mysqli prepared-statement

我正在尝试将会话值设置为与数据库中的客户引用相等,但我似乎无法让它正常工作。回显是打印0而不是正确的客户参考

这是我的代码

<?php
if (isset($_POST['Login'])) {
$loginEmail = $_POST['loginEmail'];
$loginPassword = md5($_POST['loginPassword']);
// the db should only be queried if both email and password are filled in
if (empty($loginEmail) || empty($loginPassword)) {
    $Error = "Email and Password can't be left blank";
}
else {
    $sql = "SELECT customerRef FROM customer WHERE Email=? AND Password=?";
    $stmt = mysqli_stmt_init($conn);
    if (mysqli_stmt_prepare($stmt, $sql)) {
        mysqli_stmt_bind_param($stmt, "ss", $loginEmail, $loginPassword);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_store_result($stmt);
        mysqli_stmt_bind_result($stmt, $id); 


        echo $id;
        if (mysqli_stmt_num_rows($stmt) == 2) { // this is normally 1 i just changed it to 2 so i wouldnt be redirected everytime
            // sets the session values
            $_SESSION['valid'] = true;
            $_SESSION['timeout'] = time();
            $_SESSION['username'] = $_POST['loginEmail'];
            header("Location: homepage.php");
            die();
        }
        else {
            $Error = "Username or password is incorrect";
        }
    }
}
// Close statement
$stmt->close();
// Close connection
$conn->close();
} //end of sign in isset

任何建议都将不胜感激

1 个答案:

答案 0 :(得分:1)

您实际上并未调用mysqli_stmt_fetch(),因此不会将任何内容存储到$id

来自documentation

  

当调用mysqli_stmt_fetch()来获取数据时,MySQL   客户端/服务器协议将绑定列的数据放入   指定变量var1,....

所以添加

mysqli_stmt_fetch($stmt);
致电mysqli_stmt_bind_result