简体   繁体   English

PHP mysql SELECT QUERY或一个

[英]PHP mysql SELECT QUERY with an Or

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. 基本上,我希望能够在id是一个变量的值或另一个变量的值的情况下选择它。

Thanks. 谢谢。

EDIT: The ID column is numerical. 编辑:ID列是数字。

I think you forgot the last ' character 我想你忘了最后一个字符

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

but because the id column is numerical, you should use: 但是由于id列是数字列,因此您应该使用:

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

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");

However, this solution has very very bad code smell! 但是,此解决方案具有非常非常不好的代码味道!

First off, this is why IN exists: to be able to write 首先,这就是IN存在的原因:能够写

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

And second, are you injecting unescaped strings into your query? 其次,您是否将未转义的字符串注入查询? If you are, your code is vulnerable to sql injection ! 如果是这样,您的代码很容易受到sql注入的攻击! 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);

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. 脚注:我知道使用sprintf时,也可以只使用%d代替%s作为格式说明符,从而处理整数值。 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?). 但是,我认为只要查看一个位置(参数列表)而不是多个位置(是否对变量使用intval ?),就可以证明您正确地对变量进行转义(也许我没有,但是我正在使用%d中的格式字符串,这样我还是可以吗?)。 It may sound counter-intuitive, but it's more robust in the face of modifications. 听起来可能违反直觉,但面对修改时它会更健壮。

Try this: 尝试这个:

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

I recommend you use mysql_error() for get mysql errors(if exists). 我建议您使用mysql_error()获取mysql错误(如果存在)。

mysql_query( .. ) or die('Erro:'.mysql_error());

the mysql_error returns the last error occurred in mysql. mysql_error返回mysql中发生的最后一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM