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
  • 739
  • 3
  • 12
  • 25
  • 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
  • 49,547
  • 13
  • 120
  • 153
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
  • 332,285
  • 67
  • 532
  • 628
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.
  • 101,727
  • 34
  • 178
  • 212
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,816
  • 9
  • 61
  • 81
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,470
  • 5
  • 40
  • 63
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
  • 47,289
  • 11
  • 75
  • 111
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
  • 854,459
  • 170
  • 1,222
  • 1,395