PHP Search MySQL

I have a database query:

$result=mysql_query("SELECT * FROM table WHERE name like '%$search%'") or die(" <b>  </b> ");

and database itself:
alt text

After trying, the search began to find only the query “First Name” or “Last Name” (((

Search should find queries like this:

First name Last name
Last name First name
Surname
Name

In the database, the name column stores information like this: First Name Last Name

It finds a lot of people on the request “Name” and displays them successfully.

Any of the options above can be passed to the $search variable.

:


Answer 1, authority 100%

$parts = explode(" ", $search);
$result=mysql_query("SELECT * FROM table WHERE name like '".mysql_real_escape_string("%".$parts[0]."%").isset($parts[1])?" AND name like '".mysql_real_escape_string("%".$parts[1]."%")."'":'') or die(" <b>  </b> ");

something like this

UPD
Yes, I agree, corrected. But you might as well find the blunder yourself 🙂


Answer 2

in code suggested by @shurik

$parts = explode(" ", $search);
$result=mysql_query("SELECT * FROM table WHERE name like '".mysql_real_escape_string("%".$parts[0]."%").isset($parts[1])?" AND name like '".mysql_real_escape_string("%".$parts[1]."%")."'":'') or die(" <b>  </b> ");

SQL considers the possibility when there is a first and last name in the query, but what if there is only one part? Then we do not have a space on which we could hit the string, so the pattern is collected here like this “%%”, which leads to a MySQL error, which is observed by the author of the question.
Accordingly, if we add a skeleton check for a space at the beginning, I think it will work. Total replace part

$parts = explode(" ", $search);

for the variant with a check:

$parts = array();
if (strpos($search, ' ')) {
    $parts = explode(" ", $search);    
} else {
    $parts[] = $search;
}