Home > Article > Backend Development > How to query products under a specific category with PHP?
Title: How to query products under a specific category with PHP? Detailed code sample sharing
In the development of e-commerce websites, it is necessary to frequently query product information under specific categories in order to display it to users. PHP, as a popular back-end programming language, can help us achieve this function. This article will introduce in detail how to query products under a specific category in PHP and provide specific code examples.
First, we need to create a database table to store product information, including product ID, name, price, classification and other information. Suppose we have a table named products
with the following structure:
CREATE TABLE products ( id INT PRIMARY KEY, name VARCHAR(100), price DECIMAL(10, 2), category_id INT );
In this table, the category_id
field is used to indicate the category to which the product belongs. Next, we will insert some sample data:
INSERT INTO products (id, name, price, category_id) VALUES (1, '商品1', 100.00, 1), (2, '商品2', 150.00, 2), (3, '商品3', 80.00, 1), (4, '商品4', 120.00, 3), (5, '商品5', 200.00, 2);
Next, we need to write PHP code to query products under a specific category. The following is a sample code:
<?php // 连接数据库 $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "ecommerce"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("数据库连接失败: " . $conn->connect_error); } // 查询特定分类下的商品 $category_id = 1; // 假设这里查询分类ID为1的商品 $sql = "SELECT * FROM products WHERE category_id = $category_id"; $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "商品ID: " . $row["id"] . " - 名称: " . $row["name"] . " - 价格: $" . $row["price"] . "<br>"; } } else { echo "未找到与该分类匹配的商品"; } $conn->close(); ?>
In this code, we first connect to the database, and then specify the category ID to be queried as 1. Then, execute the SQL query statement and traverse the query results and output them to the page.
Through the above code example, we can query product information under a specific category in PHP. Developers can customize and expand accordingly according to actual needs to achieve more complex query functions. I hope this article can help readers who are learning PHP so that they can better understand how to use PHP to handle the product classification query function in e-commerce websites.
The above is the detailed content of How to query products under a specific category with PHP?. For more information, please follow other related articles on the PHP Chinese website!