Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching rows from database via a prepared statement [duplicate]

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));
like image 223
at010 Avatar asked May 12 '26 17:05

at010


1 Answers

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));
like image 95
meda Avatar answered May 16 '26 17:05

meda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!