I’ve made a search box feature that allows me to type in a word and then it finds any matches of the word in my database. However, it only finds EXACT matches. I’m looking for suggestions on how to make the search better.
The code below is what i currently use for searching the databases for users that might be matches for the user searching.
$search_keys = array('fname', 'lname', 'email' );
foreach ( $search_keys as $key )
{
$result = mysql_query( "SELECT id FROM users WHERE " . $key . " LIKE " . "\"{$str}\"" ) or die(mysql_error());
while ( $row = mysql_fetch_array( $result ) )
{
// Get the User
$tmp_user = new User();
$tmp_user->getUserById( $row['id'] );
// Add User to list of potential candidates
array_push($users, $tmp_user);
}
}
I see two points where you can improve your code fragment. But first of all take care that $str is properly formatted to be safely used in your SQL query. Otherwise you will run into a problem called SQL Injection. I assume that now for your code.
Please see the example code which contains both suggestions. First the SQL query is build. There is only need to run one query for all (three) fields instead of one query per field. That’s useful if you extend your search later.