PHP Development Practice: Using PHP and MySQL to Implement Product Search Function
Search function is an essential part of modern e-commerce websites. This article will introduce how to use PHP and MySQL to implement basic product search functions. We'll use a simple example to illustrate this process.
Step 1: Create a database
First, we need to create a database to store product information. Assume that our database is named "store" and contains a table named "products". The table structure is as follows:
CREATE TABLE products
(
id
int(11) NOT NULL AUTO_INCREMENT,
name
varchar(255) NOT NULL,
description
text NOT NULL,
price
decimal(10,2) NOT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Step 2: Write HTML page
Next, we need to write an HTML page to allow users to enter search keywords. The sample code is as follows:
<title>商品搜索</title>
<h1>商品搜索</h1> <form action="search.php" method="GET"> <input type="text" name="keyword" placeholder="请输入关键词"> <input type="submit" value="搜索"> </form>
Step 3: Write PHP search processing code
After the user submits the search keyword, we need to write PHP code to handle search requests and query matching product information from the database. The sample code is as follows:
// 连接数据库 $conn = mysqli_connect("localhost", "root", "", "store"); // 检查连接是否成功 if (mysqli_connect_errno()) { echo "连接数据库失败" . mysqli_connect_error(); exit; } // 获取用户输入的关键词 $keyword = $_GET['keyword']; // 查询匹配的商品 $query = "SELECT * FROM products WHERE name LIKE '%$keyword%' OR description LIKE '%$keyword%'"; $result = mysqli_query($conn, $query); // 输出商品列表 while ($row = mysqli_fetch_assoc($result)) { echo "<h2>" . $row['name'] . "</h2>"; echo "<p>" . $row['description'] . "</p>"; echo "<p>价格:" . $row['price'] . "</p>"; echo "<hr>"; } // 释放结果集 mysqli_free_result($result); // 关闭数据库连接 mysqli_close($conn);
?>
The above code first connects to the database, then gets the keywords entered by the user, and uses the LIKE statement to Query matching product information in the database. Finally, the query results are output through a loop.
Summary
Through the introduction of this article, we have learned how to use PHP and MySQL to implement the product search function. First, we created a database table to store product information, and then wrote an HTML page to receive user search requests. Finally, the search request is processed through PHP code, and the matching product information is queried from the database and output to the page.
Of course, this is just a simple example, and actual development may involve more complex functions and designs. However, through this example, we can master the implementation method of the basic product search function, and carry out further development and optimization on this basis.
The above is the detailed content of PHP development practice: using PHP and MySQL to implement product search function. For more information, please follow other related articles on the PHP Chinese website!