Search code examples
phpmysqliprepared-statement

Fetching rows from database via a prepared statement


I want to use prepared statements to retrieve some result from the database and have tried the below. But It always returns []. Is this the correct way to return rows via a prepared statement?

$stmt = $con->prepare('SELECT bookingId,locationName
    FROM bookings
    WHERE username= ?');
$stmt->bind_param('s', $one);
$stmt->execute();
$stmt->bind_result($id, $loc);
$output = array();
while($row = $stmt->fetch()){
    $output[] = $row;
}
$stmt->close();

print(json_encode($output));

Solution

  • Problem:

    Unlike PDO in mysqli the function fetch() does not return a row, it just returns a boolean or NULL, check the docs:

    #Value  Description
    #TRUE   Success. Data has been fetched
    #FALSE  Error occurred
    #NULL   No more rows/data exists or data truncation occurred
    

    Solution

    $sql = '
    SELECT bookingid, 
           locationname 
    FROM   bookings 
    WHERE  username = ? 
    ';
    /* prepare statement */
    if ($stmt = $con->prepare($sql)) {
        $stmt->bind_param('s', $one);
        $stmt->execute();   
        /* bind variables to prepared statement */
        $stmt->bind_result($id, $loc);
        $json = array();
        /* fetch values */
        if($stmt->fetch()) {
            $json = array('id'=>$id, 'location'=>$loc);
        }else{
            $json = array('error'=>'no record found');
        }
        /* close statement */
        $stmt->close();
    }
    /* close connection */
    $con->close();
    print(json_encode($json));