简体   繁体   中英

Unable to execute SELECT QUERY as PREPARED SQL STATEMENT in php

I get this error when I test my php file: mysqli_num_rows() expects parameter 1 to be mysqli_result

This is my php code:

<?php
require "init.php";

if(isset($_POST['username'])){
    $username = $_POST['username'];

    $stmt = "SELECT username FROM users WHERE username = ?";
    $result = $dbcon -> prepare($stmt);
    $result->bind_param('s', $username);
    $result->execute();
    $result->bind_result($username);
    $result->fetch();

    if(mysqli_num_rows($result)==0){
        echo "Result found";
    }
    else{
        echo "NO";
    }
}
?>

Correct me if I am wrong but I believe we need such statements to prevent SQL injections.

Put a check on the outcome of the prepare :

$result = $dbcon -> prepare($stmt) or die ($dbcon->error());

And be aware that the number of rows is often zero if you do not call store_result , but in your case you can just check the return value of the fetch call, so join the fetch with your if :

if ($result->fetch()) {
   echo "Result found";
} else {
    echo "NO";
}

... and drop the use of num_rows .

It is not related to your problem, but it's good practice to add a close once you don't need the prepared statement anymore:

$result->close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM