PHP sql语句搜索数据库中的用户名

I am trying to construct an sql query to search my database for users. It is supposed to help users to find other users on my website to find friends.

I did some research because I knew I did not want:

$query = "SELECT userName, userID FROM user WHERE userID = $userName ";

Because it would not be an effective search if they had to type the users exact name in to find them.

After doing some research I decided to try the like term with % symbols in front and back so it could be the name with lets say numbers before or after and it would show up.

The example I found online formatted it like this:

$query = "SELECT userName, userID FROM user WHERE userID Like '%{$userName}%' ";

but when I executed this query while implemented on m y website, I ran into problems of it returning to many results. It returned results that did not include anything within my search term.

I also tried the above search query with out the brackets since I did not understand why I needed them but I got the same results.

Any suggestions on how to make the search a little stricter using the above command query?

Or any other suggestions for how I should search my database for a user to friend?

The % sign is for wildcards. So if $userName = 'apple' your query would match apple, applepie, and crabapple but not appl.

If you want an exact match remove the %s or the LIKE altogether.

Consider the strings

Apple iApple Apple Product

If you type Apple

Like '%{$userName}%' "

Returns: Will return you Apple, iApple , Apple Product
Reason: The % on both side indicates it will accept any text before and after your search term

Like '{$userName}%' "

Returns: Will return you Apple and Apple Product
Reason: The % on right side indicates it will accept any text after your search term

Like '%{$userName}' "

Returns: Will return you Apple and iApple
Reason: The % on left side indicates it will accept any text before your search term

Like '{$userName}' "

Returns: Will return you Apple
Reason: No % will restrict the search to the search term

Further More

I believe your query should be

  $username = mysqli_real_escape_string($userName);
  $query = "SELECT userName, userID FROM user WHERE userName Like '%{$username}%'";

Please try this. also why are you using braces..

$query = "SELECT userName, userID FROM user WHERE username Like '%$userName%' ";