准备语句不获取/绑定任何结果。 PHP

时间:2018-03-27 08:31:30

标签: php login prepared-statement

我想用prepare语句进行此查询,但不知怎的,它不会获取任何数据。我在表单中输入的用户名在数据库中,我想问题必须在prepare stmt中的某个地方。

if(isset($_POST['login'])){

    $typed_username = mysqli_real_escape_string($connection, $_POST['login_username']);
    $typed_password = $_POST['login_password'];

    $column        = "username";

    $stmt = mysqli_prepare($connection, "SELECT user_password FROM users WHERE ? = ?");
    mysqli_stmt_bind_param($stmt, "ss", $column, $typed_username);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $user_password);

    if(mysqli_stmt_num_rows($stmt) < 1){
        echo "no results";
    }

    if(password_verify($typed_password, $user_password)){

        echo "login yeah!";

    }
}

无论我尝试什么,我都会“无结果”。

1 个答案:

答案 0 :(得分:1)

虽然我已经添加了关于如何解决这个问题的评论,但我想你的学习目的我应该在这里添加解决方案。

如果$column = "username";永不改变,这将成为一个非常简单的解决方案。

如果是这样的话;你必须改变你的准备:
$stmt = mysqli_prepare($connection, "SELECT user_password FROM users WHERE ? = ?");
对此:
$stmt = mysqli_prepare($connection, "SELECT user_password FROM users WHERE username = ?");

在更改之后,您不再需要绑定$column(mysql表示绑定列无论如何都是没有意义的,因为它不会接受它。) 因此,您的bind_param更改为:
mysqli_stmt_bind_param($stmt, "ss", $column, $typed_username);
对此(您不再需要myqsli_real_escape_string,因此您可以将$_POST直接放入查询中:
mysqli_stmt_bind_param($stmt, "s", $_POST['login_username']);

因此,您的整体代码现在看起来像:

 if(isset($_POST['login'])){

    $typed_password = $_POST['login_password'];

    $stmt = mysqli_prepare($connection, "SELECT user_password FROM users WHERE username = ?");
    mysqli_stmt_bind_param($stmt, "s", $_POST['login_username']);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $user_password);
    //you where missing fetch
    mysqli_stmt_fetch($stmt);

    //store the result
    mysqli_stmt_store_result($stmt);
    //now we can use mysqli_stmt_num_rows
    if(mysqli_stmt_num_rows($stmt) < 1){
        echo "no results";
    }
    //added an else here as I said in the comments
    else if(password_verify($typed_password, $user_password)){

        echo "login yeah!";

    }
}