Home  >  Article  >  Database  >  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
Linda HamiltonOriginal
2024-11-12 12:11:02928browse

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);

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

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!

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