Matthew Smart
Matthew Smart

Reputation: 3

What is the proper syntax for inserting variables into a SELECT statement?

I believe I have a simple syntax problem in my SQL statement. If I run this code, I get an error in the database query.

$user = $_GET['linevar'];
echo $user;  // testing - url variable echos correctly
$sql = "SELECT * FROM `userAccounts` WHERE `name` = $user";
$result = mysql_query($sql) or die("Error in db query");

If I replace $user in the $sql string with 'actualName' or a known record in my table, the code works fine. Am I using the $ variable incorrectly in the SQL string?

Upvotes: 0

Views: 130

Answers (3)

Edd Slipszenko
Edd Slipszenko

Reputation: 396

This should work:

$sql = "SELECT * FROM `userAccounts` WHERE `name` = '" . $user . "'";

Upvotes: 1

xdazz
xdazz

Reputation: 160883

You need escape the get input, then quote it.

// this is important to prevent sql injection.
$user = mysql_real_escape_string($_GET['linevar']);

$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";

Upvotes: 1

nickb
nickb

Reputation: 59709

You need to surround the value that you're getting from $user with quotes, since it's probably not a number:

$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";

Just as a note, you should also read up on SQL injection, since this code is susceptible to it. A fix would be to pass it through mysql_real_escape_string():

$user = mysql_real_escape_string( $_GET['linevar']);

You can also replace your or die(); logic with something a bit more informative to get an error message when something bad happens, like:

or die("Error in db query" . mysql_error());

Upvotes: 1

Related Questions