当有两个匹配数据时,只获得一个Jsonobject响应



我写了下面的PHP代码来从我的数据库中获取多个JSON对象:

<?php
$connection = new mysqli("localhost","root","","Fubon");
$dateCheckSQLCommand = $connection->prepare("select * from clockindata where Month(date)= 11 ");
$dateCheckSQLCommand -> execute();
$result = $dateCheckSQLCommand->get_result();
$rowOfDate = $result->fetch_assoc();
echo json_encode($rowOfDate);

当我运行下面这样的PHP文件时,我希望得到两个JSON对象,因为我的MySQL中有两个月11的数据匹配:

[{"account":"Fu","ssid":"Fu","date":"2019-11-14 00:00:00"},{"account":"Fu","ssid":"Fu","date":"2019-11-21 00:00:00"}]

但我只得到一个JSON对象,如下所示:

{"account":"Fu","ssid":"Fu","date":"2019-11-14 00:00:00"}

如何解决这个问题?

您需要获取结果中的每一行。您在代码中只调用了fetch_assoc()一次。您需要循环直到fetch_assoc()返回false,或者使用fetch_all()(仅由mysqlnd驱动程序支持(

$connection = new mysqli("localhost","root","","Fubon");
$dateCheckSQLCommand = $connection->prepare("select * from clockindata where Month(date)= 11 ");
$dateCheckSQLCommand -> execute();
$result = $dateCheckSQLCommand->get_result();
/*** either this ****/
while($row = $result->fetch_assoc()) {
$rowOfDate[] = $row;
}
/*** or this, if it's supported ***/
$rowOfDate = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($rowOfDate);

不过,最好的解决方案是更改您正在使用的数据库API。Mysqli对用户不是很友好,并且是作为MySQL的C API的低级一对一映射编写的。即使使用PDO,这是PHP的另一个内置数据库API,也会使代码更容易使用。下面是它的样子,包括一个参数化的安全查询:

$month = 11;
$db = new PDO("mysql:host=localhost;dbname=Fubon", "root", "of course you have a password");
$stmt = $db->prepare("SELECT * FROM clockindata WHERE MONTH(`date`) = ?");
$stmt->execute([$month]);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
// if your script is outputting JSON, set the MIME type appropriately
header("Content-Type: application/json");
echo json_encode($data);

尤其是当你在查询中使用参数时(当然,你已经是了,对吧?(PDO变得比Mysqli更容易使用。

最新更新