Multiple columns after a WHERE in PHP?
Question
Hey all, just a quick question (should be an easy fix I think). In a WHERE statement in a query, is there a way to have multiple columns contained inside? Here is my code:
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and pwd='$pass'";
What I want to do is add another column after the WHERE (called priv_level = '$privlevel'). I wasn't sure of the syntax on how to do that however.
Thanks for the help!
Solution
Read up on SQL. But anyways, to do it just add AND priv_level = '$privlevel'
to the end of the SQL.
This might be a pretty big step if you're new to PHP, but I think you should read up on the mysqli
class in PHP too. It allows much safer execution of queries.
Otherwise, here's a safer way:
$sql = "SELECT * FROM $tbl_name WHERE " .
"username = '" . mysql_real_escape_string($myusername) . "' AND " .
"pwd = '" . mysql_real_escape_string($pass) . "' AND " .
"priv_level = '" . mysql_real_escape_string($privlevel) . "'";
OTHER TIPS
Wrapped for legibility:
$sql="
SELECT *
FROM $tbl_name
WHERE username='$myusername' and pwd='$pass' and priv_level = '$privlevel'
";
Someone else will warn you about how dangerous the statement is. :-) Think SQL injection.
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and pwd='$pass' and priv_level = '$privlevel'";
If you prefer to not use ", try this:
$sql='SELECT * FROM '.$tbl_name.' WHERE username=\''.$myusername.'\' and pwd=\''.$pass.'\' and priv_level=\''.$privlevel.'\'';
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and pwd='$pass' AND priv_level = '$privlevel'";
On a side note: what you appear to be doing here is quite bad practice.
I think you need to add it (may be with AND) to the WHERE-clause:
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and pwd='$pass' and priv_level = '$privlevel'";
Uhm, your query already uses multiple columns in the WHERE clause :)
SQL injection issues aside (be careful):
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and pwd='$pass' and priv_level='$privlevel'";
The WHERE
clause can AND
any number of checks, so you can easily have three where you not have two, just add and priv_level='$priv_level'
at the very end.
Edit: as @thorarin's answer mention, this is a risky way to build up SQL queries, and parameter binding would be safer -- but that's orthogonal to using two vs three columns in the WHERE
clause.