I'm having a little problem here. I'm trying to display my products by category in the same page with an <h1>
before the products. I'm trying to do this with Foreign Key
but I think I'm doing something wrong and would like your help.
First I create the table for categories with this SQL code:
CREATE TABLE IF NOT EXISTS `categories` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`category_name` varchar(500) NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4;
INSERT INTO `categories` (`category_id`, `category_name`) VALUES
(1, 'Food'),
(2, 'Electronics');
Now I create the products table:
CREATE TABLE IF NOT EXISTS `products` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`product_name` varchar(500) NOT NULL,
`product_price` decimal(20, 2) NOT NULL,
`category_id` int (11) NOT NULL,
FOREIGN KEY (`category_id`) REFERENCES categories(`category_id`),
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4;
INSERT INTO `products` (`product_id`, `product_name`, `product_price`, `category_id`) VALUES
(1, 'Pizza', 10.50, 1),
(2, 'TV', 200.00, 2),
(3, 'Oven', 100.00, 2);
And now in the products page I'm trying to retrieve the products by category with the following code:
$sql = "SELECT p.product_id, p.product_name, p.product_price, p.category_id, c.category_name FROM products p categories c WHERE c.category_id = p.category_id ORDER BY p.category_id, p.product_name";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
$category = null;
if($num>0)
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
if($category != $category_id)
{
if(!is_null($category)) { echo "</table>"; }
echo "<h1>{$category_name}</h1>";
echo "<table>";
echo " <tr>";
echo " <th>NAME</th>";
echo " <th>PRICE</th>";
echo " <th>QUANTITY</th>";
echo " </tr>";
$category = $category_id;
}
echo " <tr>";
echo " <td><div class='product-id' style='display: none'>{$product_id}</div>";
echo " <div class='product-name'>{$product_name}</div></td>";
echo " <td>${$product_price}</td>";
echo " <td>";
echo " <form class='add'>";
echo " <input type='number' name='quantity' value='1' min='1' max='20'/>";
echo " <button type='submit'>Add to cart</button>";
echo " </form>";
echo " </td>";
echo " </tr>";
}
echo "</table>";
}
else
{
echo "No products found.<br/>";
}
The problem is that always falls on the false and I get the message "No products found."
I have searched but could not find what I'm doing wrong. I had never used Foreign Key
before.
I appreciate any help, thanks in advance!