如何通过这种方式使用外键

时间:2015-04-07 15:55:23

标签: php sql

我在这里遇到一点问题。我尝试在产品之前使用<h1>在同一页面中按类别显示我的产品。我试图用Foreign Key来做这件事,但我认为我做错了什么并希望得到你的帮助。
首先,我使用此SQL代码创建类别表:

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');

现在我创建产品表:

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);

现在在产品页面中,我尝试使用以下代码按类别检索产品:

$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>&#36;{$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/>";
}

问题在于总是落在假的上面,我得到了消息&#34;没有找到产品。&#34; 我搜索过但找不到我做错了什么。我之前从未使用过Foreign Key 感谢任何帮助,提前谢谢!

0 个答案:

没有答案