Question

I am trying to transition from literal query calls to prepared statements.

I have the following function in my class:

public function read ($identifier) {
    $stmt = static::$mysqli->prepare('SELECT * FROM `table` WHERE `id` = ?;');
    $stmt->bind_param('i', $identifier);
    $stmt->execute();

    var_dump($stmt->num_rows);
}

I know from phpMyAdmin that there is a row with id 1 in the database, but if I call read(1);, num_rows is 0.

However, if I use this logic:

public function read ($identifier) {
    $result = static::$mysqli->query('SELECT * FROM `table` WHERE `id` = '.(int) $identifier.';');
    var_dump($result->num_rows);
}

I get 1 instead.

Was it helpful?

Solution

Try call $stmt->store_result(); after the execute() call.
The result is not yet stored in memory after execute, you will either have to fetch all rows or call store_result() for the num_rows variable to show the actual number of rows affected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top