How to check no. of rows returned when using MYSQLI_STMT_PREPARE and MYSQLI_FETCH_ARRAY?

后端 未结 2 726
忘掉有多难
忘掉有多难 2021-01-14 19:50

I thought I could use MYSQLI_STMT_NUM_ROWS and MYSQLI_STMT_STORE_RESULTto check for no. of rows returned. (see commented lines ///1///, ///2///, //

相关标签:
2条回答
  • 2021-01-14 20:35
    function authenticateUser($email, $password){
        $stmt = $db->prepare("SELECT user_id, first_name, user_level, pass FROM users WHERE email=? and active is null");
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $res = $stmt->get_result();
        if($res->num_rows > 0){
            $hash = $res->fetch_object()->pass;
            if(password_verify($password, $hash)){
                return true;
            }    
        }
        return false;
    }
    

    call the function

    if(authenticateUser($_POST['email'], $_POST['password'])){
        //do something
    }
    else{
        echo "Invalid Email/Password";
    }
    
    0 讨论(0)
  • 2021-01-14 20:54

    After calling mysqli_stmt_store_result(), the MySQL driver will not permit you to operate on a result set until all rows are fetched or the result set is freed and the statement closed. So a subsequent call to mysqli_stmt_get_result() will return false, and probably result in an error like

    Commands out of sync; you can't run this command now

    which you may check with echo mysqli_error($dbc);

    Transferring the statement's result set with mysqli_stmt_get_result() will give you access to its num_rows property, so you actually don't need to use mysqli_stmt_store_result(). Instead just rely on mysqli_stmt_get_result() before checking the number of rows returned:

    if (mysqli_stmt_prepare($stmt_sel, $prep_sel)) {
         mysqli_stmt_bind_param($stmt_sel, 's', $form_email);
         mysqli_stmt_execute($stmt_sel);
    
         // Transfer the result set here:
         $result = mysqli_stmt_get_result($stmt_sel);
    
         // Then check rows returned on the $result obj
         // using mysqli_num_rows(), not mysqli_stmt_num_rows()
         if (mysqli_num_rows($result) == 1) {
           while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
              // Check your password, etc....
           }
         }
         else {
            // More than 1, do whatever you need to handle this
         }
    
         // Close it
         mysqli_stmt_close($stmt_sel);
    }
    
    0 讨论(0)
提交回复
热议问题