Jump to content

Recommended Posts

Lets say that I have a table (participant_registrations) with following columns amongst others: first_name, middle_name, last_name, full_name. full_name consists of first_name last_name and middle_name in the midddle is it is available.

 

Let's Say that I have Michael John Smith registerd. How would I set up the query so when someone searches for "Michael John Smith" or "Michael Smith" they would get the record in the results. Right no I have it set up in manner of "... WHERE full_name LIKE '%$term%' ... " which will show the record in results if you search for "Michael John Smith" but not when you search for "Michael Smith".

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/290081-how-to-properly-search-for-names/
Share on other sites

Yep, don't duplicate the First/Middle/Last into a column for Full Name. All you do is make more work and create the potential to get things out of sync. Unless, you have a legitimate business need to have a separate Full Name value. We have this in our application. We auto-populate the Report name field, but the users can put a 'modified' version of the name in the "Report name" field if they wish:

 

FirstName: Robert

MiddleName: David

LastName: Smith

ReportName: Bob Smith

 

If you don't have such a requirement - ditch the Fullname field.

 

Ideally, you would want to set up fulltext searching, but an easy workaround is to split the search string and create multiple LIKE conditions on the concatenated names.

 

Note: I used the mysql_ functions because I'm feeling lazy, you should really use mysqli_ or PDO with prepared statements

 

 

//Process the input
$searchString = $_POST['search'];
$searachWords = explode(' ', $searchString);
 
//Create the where condition for each word
$WHERE_CONDITIONS = array();
foreach($searachWords as $word)
{
    $word = mysql_real_escape_string($word);
    $WHERE_CONDITIONS[] = "CONCAT(first_name, middle_name, last_name) LIKE '%$word%'"
}
 
$query = "SELECT *
          FROM table_name
          WHERE " . implode( " OR ", $WHERE_CONDITIONS);
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.