search
HomeBackend DevelopmentPHP ProblemHow to implement search records in php

With the development of the Internet, search engines have become one of the important channels for people to obtain information. Many websites are also equipped with their own search functions to help users quickly find the content they need. PHP, as a commonly used programming language, can also implement search recording functions to provide users with a better user experience. This article will introduce how to implement PHP search records.

1. Database design

The first thing to consider is the design of the database. In this article, MySQL is used as an example.

1.1 Table design

You need to create a table to store the records searched by the user, including the following fields:

  1. id: the unique identifier of the record, automatically incremented
  2. keyword: keywords searched by the user
  3. search_time: time of the user’s search, in the format of datetime
  4. user_id: the user’s unique identifier, can be empty

The structure of the table is as follows:

CREATE TABLE search_history (
id int(11) NOT NULL AUTO_INCREMENT,
keyword varchar(255) NOT NULL DEFAULT '',
search_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
user_id int(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

1.2 Field description

In the above table, you need to pay attention to the following points:

  1. id is the primary key, automatically incremented, and used to uniquely identify a record.
  2. keyword is the keyword searched by the user and is not allowed to be empty.
  3. search_time is the time when the search occurs, the format is datetime type, and the default value is set to the current time for easy recording.
  4. user_id is the user's unique identifier, which can facilitate statistics and analysis of user behavior in some scenarios, but it is not a necessary field, so it can be empty.

2. Record search history

On the page, the user's search function can be implemented through a form. According to the search content, it is saved to the search_history table mentioned above. . The specific code is as follows:

2.1 Connect to the database

First you need to connect to the database in order to store the search results in the database.

$conn = mysqli_connect('localhost', 'root', 'password', 'database_name');
if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

}
mysqli_set_charset ($conn,"utf8mb4");

2.2 Processing search requests

Get the content entered by the user in the search box, for example:

$keyword = $_REQUEST[' keyword'];

If the user does not enter anything, there is no need to save it to the database.

if (empty($keyword)) {

return;

}

2.3 Save the search results to the database

Then, save the search results to the above The search_history table to record the user's search history.

$sql = "INSERT INTO search_history (keyword, user_id) VALUES ('$keyword', 1)";
mysqli_query($conn, $sql);

In the above code , save the searched keyword and user's unique identifier (tentatively 1) to the keyword and user_id fields in the search_history table.

3. Display search history

If you need to display the search history on the website, you can obtain it by querying the search_history table in the database. Below we will introduce how to implement this function through PHP.

3.1 Query the database

$conn = mysqli_connect('localhost', 'root', 'password', 'database_name');
if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

}
mysqli_set_charset($conn,"utf8mb4");

$sql = "SELECT * FROM search_history ORDER BY search_time DESC LIMIT 10";
$result = mysqli_query($conn , $sql);

The above code first connects to the database and queries all records in the search_history table, arranges them in reverse chronological order, and obtains the top 10 most recent records.

3.2 Obtain historical records

Next, loop through the obtained records and output them to the page.

if (mysqli_num_rows($result) > 0) {

while($row = mysqli_fetch_assoc($result)) {
    echo $row["keyword"];
}

} else {

echo "暂无搜索历史记录";

}

The above code first determines whether the query result is Empty. If it is not empty, the keywords of each record will be output to the page through loop traversal. If it is empty, prompt information will be output.

4. Delete search history

If the user needs to delete some search history, he can clear the records that need to be deleted from the database by adding a "Delete" button on the page.

4.1 Connecting to the database

The operation is the same as above and will not be repeated here.

$conn = mysqli_connect('localhost', 'root', 'password', 'database_name');
if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

}
mysqli_set_charset ($conn,"utf8mb4");

4.2 Processing deletion requests

Get the id of the record that the user needs to delete and delete it from the database.

$id = $_REQUEST['id'];

if (!empty($id)) {

$sql = "DELETE FROM search_history WHERE id='$id'";
mysqli_query($conn, $sql);

}

If id is If empty, no action is required.

5. Summary

Through the above introduction, we can find that the implementation of PHP search records mainly needs to revolve around the design of the database. By setting the corresponding fields in the table, the search results and recording time are stored in the database to facilitate query and exhibit. Of course, you need to pay attention to security issues and avoid SQL injection and other attacks. At the same time, if you need to implement the search record function more flexibly, you can also use other technologies, such as cookies, sessions, etc.

The above is the detailed content of How to implement search records in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version