Link to home
Start Free TrialLog in
Avatar of lepirtle
lepirtle

asked on

MySQL WHERE syntax using POST variable

I am trying to write an SQL statement that fetches the value in the "userkey" field when the "username" and "userpassword" are equal. The "username" and "userpassword" are contained in variables passed using $_POST. The statement follows:
$sql = "SELECT userkey FROM tbl_name WHERE (username = ".$_POST['username'].") AND (userpassword = ".$_POST['password'].")";

Assuming the username is "John", the results of the above query is:
Unknown column 'john' in 'where clause'

Might someone correct my syntax to yield the desired results: the userkey?
Thanks.
Avatar of maeltar
maeltar
Flag of United Kingdom of Great Britain and Northern Ireland image

Firstly you should always use some method of preventing SQL Injection, no matter how simple..

$uname = mysql_real_escape_string($_POST['username']);
$pass = mysql_real_escape_string($_POST['password']);

$sql = "SELECT userkey FROM tbl_name WHERE username = '{$uname}' AND userpassword = '{$pass}'");

Open in new window


try that

Regards

S
Avatar of lepirtle
lepirtle

ASKER

Hi Maeltar,
I appreciate, and will incorporate your Injection statements.

I tried your revised sql statement and initially received an error:
Parse error: syntax error, unexpected ')'

So I removed the last ')' but now, when I echo the $userkey I receive the word "Array'.

$uname = mysql_real_escape_string($_POST['username']);
$pass = mysql_real_escape_string($_POST['password']);

$sql = "SELECT userkey FROM tbl_name WHERE username = '{$uname}' AND userpassword = '{$pass}'";

$result_set = mysql_query($sql) or die(mysql_error());

$userkey = mysql_fetch_array($result_set);

echo $userkey;

Am I wrong in using the following to display the userkey?

 $userkey = mysql_fetch_array($result_set);
 echo $userkey;

Avatar of Dave Baldwin
Here http://www.phpeasystep.com/workshopview.php?id=6 is a script similar to one I use.  Note the addition at the bottom of the page about encrypting the password.  It is generally considered bad to store passwords in plain text in your database.
ASKER CERTIFIED SOLUTION
Avatar of maeltar
maeltar
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Malter. That did the trick!