从数据库中的产品生成JSON,仅占用最后一行

时间:2014-11-14 18:02:41

标签: php mysql json

这些列在名为" products"

的表格中设置如下
+------------++---------------++----------------------++---------------++----------------+
| product_id  | product_name   | product_description   |  product_image |  product_price |
+------------++---------------++----------------------++---------------++----------------+
|      1      |     a1         |    good               |     url.jpg    |     150dkk     |
+------------++---------------++----------------------++---------------++----------------+
|      2      |     a2         |    nice               |     url.jpg    |     150dkk     |
+------------++---------------++----------------------++---------------++----------------+

然后这是我的代码,所以我遍历我的products表并将它们推送到一个JSON数组。

    //Create an array
    $json_response = json_decode('{"products":[]}');

    $sql = "SELECT * FROM products";
    $result = $conn->query($sql);
    while($row = mysqli_fetch_array($result)){
    $row_array['id'] = $row['product_id'];
    $row_array['name'] = $row['product_name'];
    $row_array['description'] = $row['product_description'];
    $row_array['image'] = $row['product_image'];
    $row_array['price'] = $row['product_price'];
}
    // Push the columns into the created array
    array_push($json_response->products, $row_array);

    // Encode into an object
    $oJsonResponse = json_encode($json_response);

    // Save it in a new file that holds the json from MySQL
    file_put_contents('products.json', $oJsonResponse);

问题是我只设法将id为2的产品放入我的json文件中,这样第一个产品就永远不会保存在.json文件中。当我做echo = "$row[product_name]";时 - 我得到了两个产品

1 个答案:

答案 0 :(得分:2)

在这里(将array_push移动到while循环中)

<?php

//Create an array
$json_response = array();

$sql = "SELECT * FROM products";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result)) {
    $row_array['id'] = $row['product_id'];
    $row_array['name'] = $row['product_name'];
    $row_array['description'] = $row['product_description'];
    $row_array['image'] = $row['product_image'];
    $row_array['price'] = $row['product_price'];

    // Push the columns into the created array
    $json_response[] = $row_array;
}

// Encode into an object
$oJsonResponse = json_encode($json_response);

// Save it in a new file that holds the json from MySQL
file_put_contents('products.json', $oJsonResponse);