php sql查询中的php变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10127667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:26:57  来源:igfitidea点击:

php variable in sql query

phpsqlvariables

提问by Jonh Camel

I have this:

我有这个:

$result = mysql_query("SELECT * FROM animals WHERE hand= " .$_SESSION['SESS_HAND']. ");

But always shows "Parse error: parse error, expecting T_STRING' orT_VARIABLE' or `T_NUM_STRING"

但总是显示“解析错误:解析错误,期待T_STRING' orT_VARIABLE' 或 `T_NUM_STRING”

回答by a1ex07

Always escape string variables :

总是转义字符串变量:

$result = mysql_query("SELECT * FROM animals WHERE hand= '" .
mysql_real_escape_string($_SESSION['SESS_HAND']). "'");

回答by e--

The reason your query does'nt work is because the value of your WHERE is'nt between single quotes.

您的查询不起作用的原因是因为您的 WHERE 的值不在单引号之间。

EDIT: Quentin is right too, you did'nt close the quotes at the last bracket ;).

编辑:昆汀也是对的,你没有在最后一个括号处关闭引号;)。

This would make the query work:

这将使查询工作:

$result = mysql_query("SELECT * FROM animals WHERE hand= '" .$_SESSION['SESS_HAND']. "'");

But like a1ex07 points out, you should allways escape variables! Above query is vulnerable to MySQL injections. Underneath example shows the correct way by escaping the variable, and in my opinion is a bit better readable code ;).

但是就像 a1ex07 指出的那样,您应该始终对变量进行转义!上面的查询容易受到 MySQL 注入的影响。下面的示例通过转义变量显示了正确的方法,在我看来,代码可读性更好;)。

$query = "SELECT * FROM `animals` 
WHERE `hand` = '" .mysql_real_escape_string($_SESSION['SESS_HAND']). "'";

mysql_query($query);

回答by Quentin

It gives that error message because you never finish the string that you try to append after the session data: ");.

它给出了错误消息,因为你永远不,你尝试会话数据后,追加完成字符串:");

Don't build SQL queries by mashing together strings though. Use prepared statements and parameterized queries.

不要通过将字符串混搭在一起来构建 SQL 查询。使用准备好的语句和参数化查询

回答by d-_-b

try:

尝试:

$result = "SELECT * FROM animals WHERE hand= " . $_SESSION['SESS_HAND'];

mysql_query($result);

Also, by doing this, you can debug your query and see exactly what it's doing in SQL by writing:

此外,通过这样做,您可以调试您的查询并通过编写以下内容确切地查看它在 SQL 中的作用:

echo $result;

回答by slipfeed

Problem:

问题:

$result = mysql_query("SELECT * FROM animals WHERE hand= " .$_SESSION['SESS_HAND']. ");

Solution:

解决方案:

if (!$sessHand = mysql_real_escape_string($_SESSION['SESS_HAND']))
{ 
echo "There was a error: " . mysql_error();
}
else
{ $result = mysql_query("SELECT * FROM animals WHERE hand=$sessHand") }