【问题标题】:Get only one Jsonobject reponse while there are two match data?有两个匹配数据时只获得一个 Json Object 响应?
【发布时间】:2020-03-08 18:12:10
【问题描述】:

我编写了下面的 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_all
  • 提示:您可能希望为语句句柄使用较短的名称,例如 $stmt 在 PHP 中是传统的。这与非常冗长的$dateCheckSQLCommand 形成对比,其中 SQL 并没有真正的“命令”,而是“语句”。
  • 所提供的答案是否有帮助?如果您有这样做的声誉,您应该用 ▲ 所有答案 支持。然后,您应该标记接受 ✓ 最能回答您问题的一个答案This will mark the question as "closed," and give you some reputation on the site。如果没有一个答案令人满意,请向 cmets 提供反馈,或编辑您的问题以澄清问题。

标签: php mysql json mysqli


【解决方案1】:

您需要获取结果中的每一行。您只在代码中调用fetch_assoc() 一次。您需要循环直到 fetch_assoc() 返回 false,或者使用 fetch_all()(支持 only by the mysqlnd driver。)

$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,也会使您的代码更易于使用。这是它的外观,包括parameterized query 以确保安全:

$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 更容易使用。

【讨论】:

  • MySQLi 也有fetch_all()
  • 对,我忘记了。 IIRC 有一些问题,但我会更新答案。
  • 问题是默认情况下提供了数值数组。默认情况下,在 PDO 中,我认为两者兼而有之。
  • 我在想它是如何仅由 mysqlnd 驱动程序支持的。不知道还有多少担忧。多年来一直在使用 Laravel/Eloquent。
  • 如果有人没有 mysqlnd 驱动程序,那么这是他们的错,他们会有其他问题,例如缺少get_result()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多