[英]What is the proper syntax for inserting variables into a SELECT statement?
I believe I have a simple syntax problem in my SQL statement. 我相信我的SQL语句中有一个简单的语法问题。 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. 如果我将$user
$sql
字符串中的$user
替换$user
'actualName'
或表中的已知记录,则代码可以正常工作。 Am I using the $
variable incorrectly in the SQL string? 我在SQL字符串中错误地使用了$
变量吗?
You need to surround the value that you're getting from $user
with quotes, since it's probably not a number: 您需要用引号将从$user
获得的值括起来,因为它可能不是数字:
$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. 只是要注意,您还应该阅读SQL注入,因为此代码容易受到影响。 A fix would be to pass it through mysql_real_escape_string()
: 解决方法是将其通过mysql_real_escape_string()
传递:
$user = mysql_real_escape_string( $_GET['linevar']);
You can also replace your or die();
您也可以替换您的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());
这应该工作:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '" . $user . "'";
You need escape the get input, then quote it. 您需要转义get输入,然后引用它。
// this is important to prevent sql injection.
$user = mysql_real_escape_string($_GET['linevar']);
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.