Home >Backend Development >PHP Tutorial >How to implement classified product query function in PHP?
It is a very common and important function to implement classified product query function in PHP, especially in e-commerce websites or product display websites. Through the classified product query function, users can quickly find the products they are interested in, improve user experience, and increase website activity and conversion rate. This article will introduce how to use PHP to implement the classified product query function and provide specific code examples.
First, we need to create a database table containing product information. The following is a simple example table structure:
CREATE TABLE products ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100) NOT NULL, category VARCHAR(50) NOT NULL, price DECIMAL(10, 2) NOT NULL, description TEXT );
Next, we need to connect to the database. Here we use the MySQL database as an example. Create a file named db_connect.php
to connect to the database:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "dbname"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } ?>
Now, we will use PHP to query the products in the database Information and filtered based on user-selected categories. Create a file named index.php
and add the following code:
<?php include 'db_connect.php'; $category = $_GET['category']; $sql = "SELECT * FROM products"; if (!empty($category)) { $sql .= " WHERE category = '$category'"; } $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "商品名称: " . $row["name"]. " - 价格: " . $row["price"]. "<br>"; } } else { echo "暂无相关商品"; } $conn->close(); ?>
Finally, we need to create some category links on the page , allowing users to click on different categories to query products. Add the following code in the index.php
file:
<!DOCTYPE html> <html> <head> <title>分类商品查询</title> </head> <body> <h1>请选择一个分类:</h1> <a href="index.php">所有商品</a> | <a href="index.php?category=电子产品">电子产品</a> | <a href="index.php?category=服装鞋帽">服装鞋帽</a> | <a href="index.php?category=日用品">日用品</a> <h2>商品列表:</h2> <?php include 'index.php'; ?> </body> </html>
Now, when the user visits the index.php
page, they will see product links in different categories, click After linking, a list of products in the corresponding category will be displayed.
Through the above steps, we have successfully implemented an example of using PHP to implement the classified product query function. Users can quickly find products of their own interest based on different categories, which improves the user experience and functionality of the website.
The above is the detailed content of How to implement classified product query function in PHP?. For more information, please follow other related articles on the PHP Chinese website!