1

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!

Patrick C
  • 599
  • 3
  • 10
  • 24
  • 3
    see this question for why this is a bad idea and ways to do what you need safely: http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php – Rob Allen Jun 10 '09 at 15:17

7 Answers7

3

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) . "'";
Blixt
  • 48,513
  • 13
  • 117
  • 151
0

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.

Tomalak
  • 322,446
  • 66
  • 504
  • 612
0
$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.'\'';
KM.
  • 98,537
  • 33
  • 172
  • 205
0
$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.

Rik Heywood
  • 13,638
  • 9
  • 59
  • 79
0

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'";
Georg Leber
  • 3,252
  • 4
  • 39
  • 62
0

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'";
Thorarin
  • 45,621
  • 11
  • 72
  • 108
0

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.

Alex Martelli
  • 811,175
  • 162
  • 1,198
  • 1,373