Your problem is with the way you are using mysql_real_escape_string and sprintf
- between them they are loosing the % wildcard at the beginning and screwing up your quotes, which is why it works with multiple words but not with one.
Without seeing the echoed query string it's a bit hard to figure out what is all going on.
Far simpler to point you to the best-practice code from the manual
Add the following function to your common functions include (I hope you've got one - you should have)
function quote_smart($value)
{
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote if not integer
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
You then use it like this
$query = sprintf("SELECT part_field1, field2, field3, field4
FROM table
WHERE field2
LIKE %s
ORDER BY field1",
quote_smart('%' . $field2 . '%'));
You will now have a query string that is protected from sql injection attacks, properly quoted and with the wildcards % in place to match anywhere in the text.