PHP Mysql Search Query

17,893

Solution 1

Try using concat:

$q = "SELECT * FROM `members` WHERE `first_name` LIKE :search_string 
OR `last_name` LIKE     :search_string 
OR concat(`first_name` , ' ', `last_name`) LIKE :search_string";

Solution 2

SELECT * 
FROM `members` 
WHERE `first_name` LIKE :search_string 
   OR `last_name` LIKE :search_string 
   OR `first_name` AND `last_name` LIKE :search_string;

ANDis an operator not a concatenator.

SELECT * 
FROM `members` 
WHERE `first_name` LIKE :search_string 
   OR `last_name` LIKE :search_string 
   OR CONCAT(`first_name`,' ', `last_name`) LIKE :search_string;

Solution 3

So what you do no is:

User enters 'First Last'

You search :

First like '%First Last%' or Last  like '%First Last%' ...

You need to use full text search index.

http://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html

or something like

http://sphinxsearch.com/

Share:
17,893

Related videos on Youtube

Admin
Author by

Admin

Updated on September 15, 2022

Comments

  • Admin
    Admin over 1 year

    Hello i have a simple search query, what i'm facing is when someone writes the only first name of the user that he wants to search, my query finds it, also when someone only writes the last name in the input and posts it, it also shows that too, but when user writes first name and last name together in the input, it can't find the user even he/she exists. The last part of $q query where i wrote first name and last name like part doesnt work i know there my logic is bad, but how can i fix that

        try {
            $q = "SELECT * FROM `members` WHERE `first_name` LIKE :search_string OR `last_name` LIKE :search_string OR `first_name` AND `last_name` LIKE :search_string";
            $q_do = $db->prepare($q);
            $q_do->execute( array("search_string"=>'%'.$query.'%') );
            $number = $db->query("SELECT FOUND_ROWS()")->fetchColumn();
        } catch(PDOException $e) {
            $log->logError($e." - ".basename(__FILE__));
        }
    

    Thank you

  • E_p
    E_p over 11 years
    Never do this. Use proper tools. Full text search any search engine would do better. Your solution would create more problems!