Using fetch_assoc on prepared statements (php mysqli)

前端 未结 3 1465
别跟我提以往
别跟我提以往 2020-11-30 14:11

I\'m currently working on a login script, and I got this code:

$selectUser = $db->prepare(\"SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?\         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 14:52

    That's because fetch_assoc is not part of a mysqli_stmt object. fetch_assoc belongs to the mysqli_result class. You can use mysqli_stmt::get_result to first get a result object and then call fetch_assoc:

    $selectUser = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
    $selectUser->bind_param('s', $username);
    $selectUser->execute();
    $result = $selectUser->get_result();
    $assoc = $result->fetch_assoc();
    

    Alternatively, you can use bind_result to bind the query's columns to variables and use fetch() instead:

    $selectUser = $db->prepare("SELECT `id`,`password`,`salt` FROM `users` WHERE `username`=?");
    $selectUser->bind_param('s', $username);
    $selectUser->bind_result($id, $password, $salt);
    $selectUser->execute();
    while($selectUser->fetch())
    {
        //$id, $password and $salt contain the values you're looking for
    }
    

提交回复
热议问题