【问题标题】:Using PDO to get JSON from tow tables使用 PDO 从两个表中获取 JSON
【发布时间】:2020-02-19 05:21:49
【问题描述】:

我正在尝试从 MySQL 数据库中的两个表中获取 JSON 对象,但没有返回任何内容。

product table: id, title, description, price
product_colors table: id, product_id, product_color

我的 PHP 代码:

$st = $conn->prepare ('SELECT `product`.id , `product`.title, `product`.description, `product`.price, GROUP_CONCAT(`product_colors`.product_color) AS colors FROM `product` LEFT JOIN `product_colors` ON `product`.id = `product_colors`.product_id GROUP BY `product`.id');


$st->execute();
$products = [];
$rows = $st->fetchAll(\PDO::FETCH_ASSOC);

foreach ($rows as $row) {
    $row['product_colors'] = explode(',', $row['product_color']);
    $products[] = $row;
}
echo json_encode ($products);

这是我想要的:

[
  {
  id: 4,
  title: 'Car',
  description: "Pellentesque orci lectus",
  price: '120$',
  product_color: ['Red', 'Blue', 'Black']
  },

  {
  id: 6,
  title: 'Bus',
  description: "orci lectus",
  price: '10$',
  product_color: ['White', 'Blue', 'Green']
  }
]

【问题讨论】:

  • 您没有在任何地方检查错误,因此您的问题可能是任何问题。您应该检查prepareexecute 是否成功,并检查是否返回了任何数据,例如count($rows) > 0

标签: php mysql arrays json mysqli


【解决方案1】:

还在考虑 PDO?你可能想要这个...

<?php

    $output = array();
    $products = 'product'; // "product" Table
    $colors = 'product_colors'; // "product_colors" Table

    //if "id" is auto-incremented which may not match "product_id", You may want to create another "product_id" in $products table to use the $statement commented below

    /*

    $statement = $connection->prepare(
        "SELECT t.product_id, t.title, t.description, t.price, c.product_color FROM `$products` t, `$colors` c WHERE t.product_id = c.product_id"
    );

    */
    $statement = $connection->prepare(
        "SELECT t.id as product_id, t.title, t.description, t.price, c.product_color FROM `$products` t, `$colors` c WHERE t.product_id = c.product_id"
    );

    $statement->execute();
    $result = $statement->fetchAll();

    foreach($result as $row)
    {
        $output['id'] = $row['product_id'];
        $output['title'] = $row['title'];
        $output['description'] = $row['description'];
        $output['price'] = $row['price'];
        $output['product_color'] = explode(',', $row['product_color']);
    }

    echo json_encode($output);

?>

【讨论】:

    【解决方案2】:

    所以最后我得到了答案,首先查询是正确和完美的,获取和循环中的错误,所以这是完美的解决方案,而且容易得多:

    $rows = array();
    while($r = mysqli_fetch_assoc($sth)) {
        $r['colors']=explode(',', $r['colors']); //colors like what i named the GROUP_CONCAT
        $rows[] = $r;
    

    【讨论】:

      猜你喜欢
      • 2018-11-25
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多