PHP mysql search multiple tables using a keyword PHP mysql search multiple tables using a keyword mysql mysql

PHP mysql search multiple tables using a keyword


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

So, you are getting result from all of the three tables, and you can identify which row came from which table by looking at its type value.


What you are probably looking for is the UNION command:

SELECT id, 'messages' as 'table' FROM messages   WHERE content LIKE '%keyword%'     OR title LIKE '%keyword%'UNIONSELECT id, 'topics' as 'table' FROM topics  WHERE content LIKE '%keyword%'     OR title LIKE '%keyword%'UNIONSELECT id, 'comments' as 'table' FROM comments  WHERE content LIKE '%keyword%'     OR title LIKE '%keyword%'


Two search in other tables you use:

SELECT `categories`.`title`, `posts`.`title` WHERE `categories`.`title` LIKE {$a} OR `posts`.`title` LIKE {$a}

The CATEGORIES and POSTS are tables of your database.