【问题标题】:Sending data from Mysql with Json using PHP使用 PHP 使用 Json 从 Mysql 发送数据
【发布时间】:2015-10-10 05:59:34
【问题描述】:

我正在尝试使用 Json 从 Mysql 数据库发送数据。只要它在数据库中只有 1 个帖子,它就可以工作,但是当它的行数更多时,它就不再工作了。

这里是 PHP 代码: // JSON 响应的数组 $response = 数组();

$data = new CDatabaseInfo();
$result = $data ->selectAll();
$data->closeDatabase();

// check for empty result
if (isset($result)) {

    $response["products"] = array();
    foreach($result as $value) {
        $product = null;
        $product = array();
        $product["pid"] = $value["pid"];
        $product["name"] = $value["name"];
        $product["price"] = $value["price"];
        $product["description"] = $value["description"];
        $product["created_at"] = $value["created_at"];
        $product["updated_at"] = $value["updated_at"];
        array_push($response["products"], $product);
    }
    // success
    $response["success"] = 1;
    echo json_encode($response, TRUE);
    echo "var dump <br>";
    var_dump($response);
}

var_dump 的结果如下:

array(2) { ["products"]=> array(2) {[0]=> array(6) { ["pid"]=> string(1) "1" ["name"]=> string(6) "Festis" ["price"]=> string(5) "20.00" ["description"]=> string(9) "God dryck" ["created_at"]=> string(19) "2015-07-09 20:31:30" ["updated_at"]=> string(19) "0000-00-00 00:00:00" } [1]=> array(6) { ["pid"]=> string(1) "4" ["name"]=> string(4) "Cola" ["price"]=> string(5) "12.00" ["description"]=> string(11) "En fin läsk" ["created_at"]=> string(19) "2015-07-20 20:29:03" ["updated_at"]=> string(19) "0000-00-00 00:00:00" } } ["success"]=> int(1) } 

谢谢!

【问题讨论】:

    标签: php mysql json


    【解决方案1】:

    没有json_encode($response, TRUE);这样的东西

    确保从数据库中获取正确的数据。除了小错误之外,您的代码应该可以正常运行。

    【讨论】:

    • 我拿走了 TRUE 但它仍然不适用于大于 1 行的数组。当它只有 1 行时,它的工作原理很完美
    • 我刚刚用 $result 中的一些随机数据运行了你的代码,它运行良好。
    • 我拿走了 $response["products"] = array();并输入: $response = array();相反,我只是输入: $response[] = $value;在 foreach 迭代中。
    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 2013-11-03
    • 2018-01-14
    • 2013-11-05
    • 2012-03-04
    • 2022-08-19
    • 1970-01-01
    • 2018-09-19
    相关资源
    最近更新 更多