Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Search First Name and Last Name

Tags:

sql

php

search

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?

like image 627
Chris Avatar asked Nov 29 '22 10:11

Chris


2 Answers

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();
like image 42
stackflow Avatar answered Nov 30 '22 23:11

stackflow


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%'");
like image 173
Number1SuperGuy Avatar answered Dec 01 '22 01:12

Number1SuperGuy