Reputation:
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
Upvotes: 3
Views: 17952
Reputation: 7
The simplest Search Query for you.. Try this its working man.
SELECT * FROM TableName
WHERE title
like '%Your Search Text%'
Upvotes: 0
Reputation: 28409
SELECT *
FROM `members`
WHERE `first_name` LIKE :search_string
OR `last_name` LIKE :search_string
OR `first_name` AND `last_name` LIKE :search_string;
AND
is 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;
Upvotes: 3
Reputation: 724
Try this:
$query = explode(" ", $query);
if(count($query)>1){
$fname = $query[0];
$lname = end($query);
}else{
$fname = $query[0];
$lname = $query[0];
}
$q = "SELECT * FROM `members` WHERE `first_name` LIKE :fname OR `last_name` LIKE :lname";
$q_do = $db->prepare($q);
$q_do->execute( array('fname' => "%$fname%", 'lname' => "%$lname%") );
Upvotes: 0
Reputation: 5084
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";
Upvotes: 11
Reputation: 3144
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
Upvotes: 1