Search code examples
phpprepared-statementbindparam

PHP bind_param not binding parameter


I am trying to search a table for specific items using a prepared statement in PHP. I am getting no errors, but also getting no record. Here is my code:

$items = [];
$search = "john";
if ($stmt = $this->con->prepare("SELECT * FROM phptest WHERE search = ?")) { //'john'";
    $stmt->bind_param("s",$search);
    $stmt->execute();
    while ($row = mysqli_fetch_array($stmt)) {
        $item = [];
        $item['id'] = $row['id'];
        $item['first'] = $row['search'];
        $item['last'] = $row['data'];
        array_push($items, $item);
    }
}
return $items;

Now, when I don't use a prepared statement, and just SELECT * FROM phptest I get all the results in the table (including the item where search = 'john'). Furthermore, if I use the query SELECT * FROM phptest WHERE search = 'john' I get the one record where search = 'john'

But as soon as I turn it into the prepared statement, I get zero errors but zero records. I do get a warning:

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given

Which made me think my bind_param or execute() was returning FALSE, but when I check, it does not appear to be returning false.

I started off my adventure working through the tutorial https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/, which I thought I understood fully but ran into my error when trying to make my own PHP API.

I then went to the manual http://php.net/manual/fr/mysqli.prepare.php, but still cannot find my error.

Though it has been closed as "off-topic," I have reviewed PHP bind_param not working and found nothing applicable to my situation.

Likewise, I am not finding the error in PHP bind_param not defined nor php bind_param is not working.


Solution

  • You're very close. mysqli_fetch_array() expects to be passed a result object, not the statement object itself:

    $stmt = $conn->prepare(...);
    $stmt->bind_param(...);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = mysqli_fetch_array($result)) {
    

    Or, in the fully OO manner:

    while ($row = $result->fetch_array()) {