mysql query select,PHP mysql SELECT QUERY或一个

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.

解决方案

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

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! 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. 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值