php - 从数据库中的产品生成 JSON,只取最后一行

标签 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     |
+------------++---------------++----------------------++---------------++----------------+

这是我的代码,所以我循环遍历我的产品表并将它们推送到一个将是 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]"; - 我得到两种产品

最佳答案

开始吧(将 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);

关于php - 从数据库中的产品生成 JSON,只取最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26936185/

相关文章:

php - 如何在 PHP 和 MySQL 中生成循环赛?

javascript - 如何重新排列 CSV/JSON 键列? (JavaScript)

php - 创建文件的文件所有权

php - 如何使base64图像保存更快?

java - 在 hibernate (springboot)中使用左连接和分页编写 sql native 查询

json - Golang 将 JSON 对象传递给函数

c# - 使用Unity JsonUtility反序列化JSON数组获取序列化值失败

php - MySQL查询以选择比x天新的记录

php - PDO 为 mysql_num_rows 准备了等效语句

mysql - 使用条件选择和求和选择不同的行