通过准备好的语句从数据库中获取行

at0*_*010 2 php json mysqli prepared-statement

我最初创建了以下查询以从我的数据库中返回一些结果。

$result = mysqli_query($con, "SELECT bookingId, locationName 
                              FROM bookings 
                              WHERE username = '$one'");
$output = array();
while($row = mysqli_fetch_assoc($result)) {
  $output[]=$row;
}
print(json_encode($output));
Run Code Online (Sandbox Code Playgroud)

但是,我现在想使用准备好的语句并尝试了以下方法。但它总是返回[]。这是通过准备好的语句返回行的正确方法吗?

$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));
Run Code Online (Sandbox Code Playgroud)

med*_*eda 5

问题:

不像PDO在mysqli函数fetch()中不返回一行,它只返回一个布尔值或 NULL,检查文档:

#Value  Description
#TRUE   Success. Data has been fetched
#FALSE  Error occurred
#NULL   No more rows/data exists or data truncation occurred
Run Code Online (Sandbox Code Playgroud)

解决方案

$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));
Run Code Online (Sandbox Code Playgroud)