Search code examples
phpmysqlibindparam

How to bind params with mysqli query


I am struggling for over an hour now with something that should be fairly simple. I want to get rows from my mysqli database and when I run my query from phpmyadmin I get expected results but when I run it (with bind_param) from my php code I get 0 results:

$sql = $connection->prepare('SELECT (UNIX_TIMESTAMP(start_time)) 
                             FROM table1 
                             WHERE UNIX_TIMESTAMP(start_time) >= ? 
                               AND (UNIX_TIMESTAMP(start_time)) <= ? 
                               AND column3 = ?') 
                            or trigger_error($connection->error, E_USER_ERROR);
$sql->bind_param('sss', $value1, $value2, $value3);
$sql->execute() or trigger_error($sql->error, E_USER_ERROR);

if ($sql->num_rows == 0){
    echo "yay";
}

Solution

  • You need to store the result set for MySQLi prepared statements. Adjust your code as follows:

    // Execute query
    $sql->execute();
    
    // Store result
    $sql->store_result();
    
    echo $sql->num_rows;
    

    PHP docs: http://php.net/manual/en/mysqli-stmt.store-result.php http://php.net/manual/en/mysqli-stmt.num-rows.php