Jump to content

What wrong here?


Orionsbelter

Recommended Posts

list($first, $last) = explode(" ", $q, 2);
$query="SELECT id, Username, First_Name, Surname FROM members WHERE fullName LIKE '%$fullName%' OR First_Name LIKE '%$first%' OR Surname LIKE '%$last%'";

 

I'm using this too search for a user. I have a input box and wanted to allow the viewer to search for a user. I wanted a script that would take apart the input text if they user enter both the forename and surname this does just that. But i also wanted it to search the database even if they only entered a forename.

 

However the problem am getting its that if they type in only a forename it will bring up all the users in the database. Most likely because it's seeing the $last variable as "" or " ".

 

Here is a quick example if i type in john smith, it brings up ONLY john smith If i type in john it brings up all the users. Even if the name is nothing alike. I want it too only bring up people with the firstname john if they only enter the forename.

 

Please help me, and maybe you can save me from pulling my hair out :D

Link to comment
https://forums.phpfreaks.com/topic/196910-what-wrong-here/
Share on other sites

If you want to check against first and last names which are seprate fields then you need to build the SQL query based on the user input, e.g. don't put blank variables into the LIKE '%$var%' part.

 

Since you have a fullname field in the database you can make it nice and simple and just use that like this:

 

$sql = "SELECT id, Username, First_Name, Surname FROM members WHERE fullName LIKE '%$fullName%'";

if(strlen($first) > 0)
{
  $sql .= " OR fullName LIKE '%$first%' ";
}
if(strlen($last) > 0)
{
  $sql .= " OR fullName LIKE '%$last%' ";
}

Link to comment
https://forums.phpfreaks.com/topic/196910-what-wrong-here/#findComment-1033745
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.