0

I am struggling to find a way to get rows from a database, based on two columns, firstName and lastName according to the search bar.

The issue is on WHERE/LIKE operators and ' ".

I am using this code below:

$search = $_POST["search"];
$query = "SELECT p.id, p.lastName, p.firstName, p.jobTitle, p.email, d.name as department, l.name as location 
            FROM personnel p 
            LEFT JOIN department d ON (d.id = p.departmentID) 
            LEFT JOIN location l ON (l.id = d.locationID) 
            WHERE p.firstName LIKE '%".$search."%' 
                OR p.lastName LIKE '%".$search."%'";

This code it's working just for one value, for example if I remove OR p.lastName LIKE '%".$search."%'.

Barmar
  • 741,623
  • 53
  • 500
  • 612
BMesc
  • 33
  • 4
  • It should work the same when searching two columns as searching one. – Barmar Jul 25 '21 at 09:59
  • I have found an answer here: https://stackoverflow.com/questions/16423905/php-select-where-like ...WHERE (p.firstName LIKE '%$search%') OR (p.lastName LIKE '%$search%')"; – BMesc Jul 25 '21 at 10:00
  • 1
    It probably won't solve this problem, but you should use a prepared query with parameters to protect against SQL injection. – Barmar Jul 25 '21 at 10:00
  • 1
    Which answer there solved it? I don't think you want to use `AND` instead of `OR`. And you shouldn't use `mysqli_real_escape_string`, you should use a prepared statement. – Barmar Jul 25 '21 at 10:02
  • 2
    You only need parentheses if you're mixing `AND` and `OR` in the condition. You don't need it with just `OR`. – Barmar Jul 25 '21 at 10:04

0 Answers0