Harvey Fletcher Harvey Fletcher - 1 year ago 71
SQL Question

Need to select from SQL where in a list

I have an SQL table and I need to select all the records where username (MM_Session) is in another users following list (Users SQL table, following column), which would look like this

username1 username2 username3 username4

So far, my SQL query looks like this:

FROM Users
WHERE Users.Following_By LIKE '" . $_SESSION['MM_Username'] . "'

Except that doesn't seem to return any values even though the user's username is in the other users following list.

Should I be using 'IN' instead of 'LIKE'?

Does anyone have any other ideas why this isn't working?


Answer Source

The LIKE operator works just the same as = if you don't use wildcard characters in your query string. Place them before and behind the word to match any occurrence of the word:

 FROM Users
 WHERE Users.Following_By LIKE '%" . $_SESSION['MM_Username'] . "%'

Though you might get more users than you expected because it matches for example foobar if MM_USERname contains only foo. You could use explicit delimiters to prevent this. Or, even better, use a separate table for the list entries and use a foreign key to join it to the Users table.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download