Brad
Brad

Reputation: 3

mysql LIKE match, but need to filter by username

I have several users that have items. I need each user to be able to search their items, and not see other people items's. This query still allows the executer to see every item in the dbase. Please help!

$findit is a variable earlier in the script that is what the user is looking for. $username is set via a session cookie after they login.

$result = mysql_query( "SELECT * FROM prices WHERE 
            itemnum LIKE '%$findit%' ||
            itemdesc LIKE '%$findit%' AND username = '$username' ORDER BY price");

Upvotes: 0

Views: 297

Answers (3)

Shi
Shi

Reputation: 4258

$result = mysql_query( "SELECT * FROM prices WHERE 
        (itemnum LIKE '%$findit%' ||
        itemdesc LIKE '%$findit%') AND username = '$username' ORDER BY price");

The brackets are missing. AND has a higher operator precedence than OR.

Upvotes: 0

Flambino
Flambino

Reputation: 18793

$result = mysql_query( "SELECT * FROM prices WHERE 
        (itemnum LIKE '%$findit%' OR itemdesc LIKE '%$findit%')
        AND username = '$username' ORDER BY price");

notice the parentheses. If they aren't there, it'll match either itemnum LIKE ... or itemdesc LIKE ... and username = ...

Upvotes: 0

Jared Farrish
Jared Farrish

Reputation: 49238

You should be able to group the OR:

SELECT * 
FROM prices 
WHERE (itemnum LIKE '%$findit%'
   OR  itemdesc LIKE '%$findit%')
  AND username = '$username'
ORDER BY price

Which will make the OR act as a single condition, and the username match as another, so that the username is required to be matched.

Upvotes: 2

Related Questions