So I have a search feature on my website and this is what the code looks like.
$search_people = mysql_query("SELECT * FROM glnce_users
WHERE f_name LIKE '%$search%' OR l_name LIKE '%$search%'");`
If i type in my search bar Chris it will bring up all of the Chris'
If I type in my search bar Olson it will bring up all of the Olson's
However if I type in Chris Olson it won't provide me results for Chris Olson even though there is a person with the First name of Chris and the Last name of olson.
What am I doing wrong?
Normal SQL,
$sql = "SELECT `id`, `first_name`, `last_name`, `mobile`, CONCAT(`first_name`, ' ',`last_name`) AS `full_name` FROM `users`
WHERE `first_name` LIKE '%".$word."%'
OR `last_name` LIKE '%".$word."%'
OR CONCAT(`first_name`, ' ',`last_name`) LIKE '%".$word."%'
OR `mobile` LIKE '%".$word."%';";
In Laravel,
$result = User::select('id', 'first_name', 'last_name', 'mobile', DB::raw('CONCAT(first_Name, " ", last_Name) AS name'))
->where('first_name', 'LIKE', '%'.$word.'%')
->orWhere('last_name', 'LIKE', '%'.$word.'%')
->orWhere(CONCAT(first_Name, " ", last_Name), 'LIKE', '%'.$word.'%')
->get();
An exploded array seems bulky and error-prone. I would recommend concatenating your database columns in the query. That way if someone has a first name with a space in it, like "Sarah Jane Albertson", it won't look for a first name of "Sarah" and a last name of "Jane" and ignore the "Albertson" entirely.
This should do what you need:
$search_people = mysql_query("SELECT * FROM glnce_users
WHERE CONCAT(f_name, ' ', l_name) LIKE '%$search%' OR l_name LIKE '%$search%'");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With