I used to spend a lot of my PHP code building complex mySQL queries. For some reason in my switch to PDO I’m also trying to write cleaner and simpler SQL – maybe because I can’t just dump the query out on an error.
Anyway, I have a function where I want to show users a specific chunk of data that applies to them, unless the user is logged in as an admin in which case the admin sees all of the data.
I was thinking of doing this:
SELECT col_a, col_b FROM some_table WHERE cond_1 = 'something' AND IF (admin_user = :logged_in_user, 1=1, userID = :logged_in_user)
Is this method considered the “correct” practice, or is it better to just use conditional logic in PHP to build the WHERE clause?
Well I would say that both could be made secure, but it seems like the MySQL solution could be more error-prone. Doing it in PHP seems like it would make more sense since PHP is probably what is handling your login sessions and the MySQL would probably be getting that data from PHP anyway. Go to the source, I say.