PHP mysql SELECT QUERY或一个 [英] PHP mysql SELECT QUERY with an Or

查看:69
本文介绍了PHP mysql SELECT QUERY或一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mysql_query("SELECT * FROM foo WHERE id ='$foo' OR id = '$foo2");

这不起作用.

基本上,我希望能够在id是一个变量的值或另一个变量的值的情况下选择它.

Basically, I want to be able to select it where the id is one variable's value OR another one's.

谢谢.

"ID"列为数字.

推荐答案

正如其他人所说并确认的那样,问题在于您正在使用字符串文字与数字列进行比较.要使其正常工作,查询应类似于

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

mysql_query("SELECT * FROM foo WHERE id =$foo OR id = $foo2");

但是,此解决方案具有非常不好的代码味道!

首先,这就是为什么 IN 存在:能够写作

First off, this is why IN exists: to be able to write

mysql_query("SELECT * FROM foo WHERE id IN ($foo, $foo2)");

第二,您要向查询中插入未转义的字符串吗?如果是这样,您的代码很容易受到 sql注入的攻击!为安全起见,请转义并引用您的变量,如下所示(在一般情况下):

And 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):

$query = sprintf("SELECT * FROM foo WHERE id IN ('%s', '%s')",
                 mysql_real_escape_string($foo),
                 mysql_real_escape_string($foo2));
mysql_query($query);

或类似的方式,因为在这种特定情况下,您知道我们正在谈论整数值:

or alternatively like this, since in this specific scenario you know we 're talking about integer values:

$query = sprintf("SELECT * FROM foo WHERE id IN (%s, %s)",
                 intval($foo), intval($foo2));
mysql_query($query);

脚注:我知道当使用这样的sprintf时,如果将%s作为格式说明符,也可以只使用%d来处理整数值.但是,我相信只要看一个地方(参数列表)而不是多个地方(是否对变量使用intval?),就可以证明您正确地对变量进行转义.在格式字符串中使用%d,这样我还是可以吗?).听起来可能违反直觉,但面对修改时,它会更健壮.

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 use intval 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.

这篇关于PHP mysql SELECT QUERY或一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆