简体   繁体   中英

Where to place WHERE clause to limit search engine

I am have issues limiting the search engine to show ONLY the data relevant to the user($comp_id). I know a WHERE clause needs to be in there somewhere, I just don't know where. please help! Thanks.

"SELECT * FROM products " .
"WHERE item_id LIKE '%".$keywords[$i]."%'".
" OR item_name LIKE '%".$keywords[$i]."%'" .
" OR class LIKE '%".$keywords[$i]."%'" .
" ORDER BY item_name";

Does it go after the first WHERE clause?

You'd want something like:

SELECT 
  *
FROM
  products 
WHERE
  (
  item_id LIKE '%".$keywords[$i]."%' OR
  item_name LIKE '%".$keywords[$i]."%' OR
  class LIKE '%".$keywords[$i]."%'
  )
  AND
  user = $comp_id
ORDER BY
  item_name

The search for keywords is in brackets, so it will find anything/all in the brackets because each criteria as OR. The AND outside the brackets separates it from the OR queries.

So anything matches in the brackets, ie if A = b OR c = d OR something else = whatever, then AND would mean explicitly whatever matched in the brackets is TRUE AND the username is something specific = TRUE as well.

You already have a WHERE clause in the statement, but you're missing a parameter that would limit the results to a particular user.

Since the database schema isn't present let's say that there is a field in the table named 'user_id' representing the user's unique id. Let's also assume that 'user_id' is an integer. In that case your SQL statement would look like this:

"SELECT * FROM products " .
"WHERE item_id LIKE '%".$keywords[$i]."%'".
" OR item_name LIKE '%".$keywords[$i]."%'" .
" OR class LIKE '%".$keywords[$i]."%'" .
" AND user_id = " . $comp_id .
" ORDER BY item_name";

In that statement we have an AND clause that is required for any match and is saying that the 'user_id' must match the value in the $comp_id variable.

This only works if the products table contains entries that are relevant to a user and a field is present there for you to query. If the table structure is more complex this won't work, and you may need to amend your question to include more data.

It looks like you've already got your answer from James. As it looks like you're taking your keywords from user input, make sure to escape your query or you'll open yourself up to a world of SQL Injection ( http://www.php.net/manual/en/mysqli.real-escape-string.php ).

Since And/Or operators are evaluated in order of appearance group the OR clauses

"SELECT * FROM products " .
"WHERE user_id = '". $comp_id."' ".
" AND (item_id LIKE '%".$keywords[$i]."%'".
" OR item_name LIKE '%".$keywords[$i]."%'".
" OR class LIKE '%".$keywords[$i]."%')".
" ORDER BY item_name";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM