PHP mysql SELECT QUERY 带有 Or
mysql_query("SELECT * FROM foo WHERE id ='$foo' OR id = '$foo2");
这是行不通的。
基本上,我希望能够在 id 是一个变量的值或另一个变量的值的情况下选择它。
谢谢。
编辑:ID 列是数字。
mysql_query("SELECT * FROM foo WHERE id ='$foo' OR id = '$foo2");
This doesn't work.
Basically, I want to be able to select it where the id is one variable's value OR another one's.
Thanks.
EDIT: The ID column is numerical.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如其他人所说并且您确认的那样,问题在于您正在使用字符串文字与数字列进行比较。为了让它工作,查询应该看起来像
但是,这个解决方案有非常非常糟糕的代码味道!
首先,这就是为什么
IN
存在:能够写入其次,您是否将未转义的字符串注入您的查询?如果是,您的代码很容易受到 sql 注入!为了安全起见,转义并引用你的变量,像这样(在一般情况下):
或者像这样,因为在这个特定的场景中你知道我们正在谈论整数值:
脚注:我知道,当像这样使用
sprintf
时,还可以通过仅使用%d
而不是 if%s
作为格式说明符来处理整数值。但是,我相信只要查看一个地方(参数列表)而不是多个地方(我是否在变量上使用了intval
?或者也许我没有),就可以证明您正确地转义了变量,但我在格式字符串中使用%d
所以我仍然没问题?)。这听起来可能违反直觉,但在面对修改时它更加稳健。As others have said and you confirmed, the problem is that you are using string literals to compare to a numeric column. To have it work, the query should look like
However, this solution has very very bad code smell!
First off, this is why
IN
exists: to be able to writeAnd second, are you injecting unescaped strings into your query? If you are, your code is vulnerable to sql injection! Escape and quote your variables to be safe, like this (in the general case):
or alternatively like this, since in this specific scenario you know we 're talking about integer values:
Footnote: I am aware that when using
sprintf
like this, one could also handle integer values by just using%d
instead if%s
as the format specifier. However, I believe that proving you are correctly escaping variables should be possible by just looking at one place (the parameter list) instead of multiple places (did I useintval
on the variable? or maybe I did not, but I 'm using%d
in the format string so I 'm still OK?). It may sound counter-intuitive, but it's more robust in the face of modifications.我认为您忘记了最后一个 ' 字符
,但由于 id 列是数字,您应该使用:
I think you forgot the last ' character
but because the id column is numerical, you should use:
试试这个:
我建议你使用 mysql_error() 来获取 mysql 错误(如果存在)。
mysql_error 返回 mysql 中发生的最后一个错误。
Try this:
I recommend you use mysql_error() for get mysql errors(if exists).
the mysql_error returns the last error occurred in mysql.