【发布时间】: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']
}
]
【问题讨论】:
-
您没有在任何地方检查错误,因此您的问题可能是任何问题。您应该检查
prepare和execute是否成功,并检查是否返回了任何数据,例如count($rows) > 0
标签: php mysql arrays json mysqli