【发布时间】:2014-05-17 16:22:11
【问题描述】:
我有一个产品数据库,每个产品都有 1 个或多个标签。比如我的查询结果是:
//Query results
product_id tag
12345 Kitchen
12345 Mixer
12345 Baking
如何显示给定产品的所有标签,并且只列出一次产品,以便我的输出类似于:
Product ID: 12345
Tags: Kitchen Mixer Baking
目前,我正在使用fetch_assoc() 并循环遍历仅显示所有内容的行。完成此任务的最佳方法是什么?
以下是我当前的代码:
$sql = <<<SQL
SELECT p.product_id, t.tag
FROM products p
JOIN tags t
ON p.product_id = t.product_id
WHERE p.product_id='12345'
SQL;
$db = new mysqli('localhost', 'user', 'password', 'dbname');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
echo $row['product_id'] . '<br>';
echo $row['tag'] . '<br>';
}
【问题讨论】: