My goal is to select all items related to a specific category from a database with PHP and MySQL. Using the script below I can select all categories with the related items.
$sql = query("SELECT bike AS 'cat_name', c.image AS 'image', p.title AS 'product_name'
FROM products p
INNER JOIN categories c
ON p.category_id = c.id");
while( $row = mysqli_fetch_array($sql)) {
echo $row['cat_name'].'<br />';
echo $row['product_name'].'<br />';
echo $row['image'];
}
This is the result:
Bike
item 1
item 2
item 3
...
Bike
item 1
item 2
item 3
...
The result above does not reflect the desired result. I would like to have only one Category selected with the related items like this:
Bike
item 1
item 2
item 3
...
Try this:
$sql = query("SELECT bike AS 'c.cat_name', c.image AS 'image', p.title AS 'product_name'
FROM products p, categories c
WHERE p.categroy_id = c.id
AND p.id = THE_ID_OF_THE_CATEGORY ");