0

I'm working on a project and am at a standstill. I've done a lot of searching around including sql documentation but can't find anything putting me in the right direction.

I've created a search form which when entering a name will show me a list of the users similar to the search term. The issue im having is that it also shows the user who's logged in and performing the search.

Here is my query -

$query = $pdo->prepare("SELECT id, first_name, last_name 
                        FROM users 
                        WHERE id <> " . $user['id'] . " 
                        AND first_name LIKE '%$searchterm%' 
                        OR last_name LIKE '%$searchterm%' 
                        LIMIT 5");

Is my statement wrong?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • 2
    You need to place your search terms in parentheses `... AND (... OR ...)` – El_Vanja Jan 16 '21 at 23:22
  • 2
    Also please note that the way you're building your query is unsafe. You're open to [SQL injection](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work). You should use [prepared statements](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) or [PDO](https://www.php.net/manual/en/book.pdo) instead. – El_Vanja Jan 16 '21 at 23:22
  • Ahhh fantastic!! Such a simple fix and ill take a look at the prepared statements and PDO, Thankyou – Ashley Watson Jan 16 '21 at 23:30
  • 1
    @El_Vanja judging from the variable name they are already using PDO... – Nick Jan 16 '21 at 23:34
  • 1
    Take a look at https://stackoverflow.com/questions/13832941/how-do-i-use-a-like-clause-in-a-pdo-prepared-statement, it will show you how to use `LIKE` with wildcards in a PDO prepared statement – Nick Jan 16 '21 at 23:34
  • @Nick Yeah, my bad, I automatically pasted one of my standard comments without editing it to fit the question. – El_Vanja Jan 16 '21 at 23:37
  • Parameterizing your query is the change that must be made. Prepared statement alone is the same as using `query()`. `SELECT id, first_name, last_name FROM users WHERE id <> ? AND (first_name LIKE ? OR last_name LIKE ?) LIMIT 5` – user3783243 Jan 16 '21 at 23:58

0 Answers0