Home > Database > Mysql Tutorial > How to Combine Multiple Table Searches in PHP with MySQL and a Keyword?

How to Combine Multiple Table Searches in PHP with MySQL and a Keyword?

Linda Hamilton
Release: 2024-11-12 12:11:02
Original
945 people have browsed it

How to Combine Multiple Table Searches in PHP with MySQL and a Keyword?

Combining Multiple Table Searches in PHP with MySQL and a Keyword

You have a database with three tables: messages, topics, and comments. Each table contains two fields, 'content' and 'title'. Your goal is to perform a single search query that searches through all six fields (messages.content, messages.title, topics.content, topics.title, comments.content, comments.title) using a specified keyword.

To accomplish this, modify your query to use multiple UNION statements. Each UNION statement will search a specific table using the LIKE operator for the keyword within the 'content' and 'title' fields. The following updated query combines all three searches:

$query = "(SELECT content, title, 'msg' as type FROM messages WHERE content LIKE '%" . $keyword . "%' OR title LIKE '%" . $keyword ."%') 
UNION
(SELECT content, title, 'topic' as type FROM topics WHERE content LIKE '%" . $keyword . "%' OR title LIKE '%" . $keyword ."%') 
UNION
(SELECT content, title, 'comment' as type FROM comments WHERE content LIKE '%" . $keyword . "%' OR title LIKE '%" . $keyword ."%')";

mysql_query($query);
Copy after login

This query uses the UNION operator to combine the results of each SELECT statement into a single result set. The added 'type' field indicates which table the row originated from.

"msg" = messages table
"topic" = topics table
"comment" = comments table
Copy after login

The above is the detailed content of How to Combine Multiple Table Searches in PHP with MySQL and a Keyword?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template