如何在mysql查询的'IN'子句中使用PHP中的值数组?

时间:2011-03-06 00:07:17

标签: php mysql

//get all id's of ur friend that has installed your application
 $friend_pics=$facebook->api( array( 'method' => 'fql.query', 'query' => "SELECT uid FROM user WHERE uid   IN(SELECT uid2 from friend WHERE uid1='$user') AND is_app_user = 1" ) ); // this query work fine
//your top10 friends in app
$result="SELECT * FROM fb_user WHERE user_id IN($friend_pics) ORDER BY oldscore DESC LIMIT 0,10";
db_execute($result);

我想从存储在oldscore中的数据库中检索十位最佳射手,但在我的第二次查询中,数组名称$ friend_pics无法正常工作我猜,PLZ帮助我谢谢

3 个答案:

答案 0 :(得分:3)

没有原生支持。即使绑定参数API也不允许使用IN子句的数组。您必须使用一些帮助程序代码构造查询:

$friend_pics = array_map("mysql_real_escape_string", $friend_pics);
$friend_pics = "'" . implode("', '", $friend_pics) . "'";
"SELECT * WHERE user_id IN ($friend_pics)              "

更简单的替代方案是mysqls FIND_IN_SET()但是:

$friend_pics = mysql_real_escape_string(implode(",", $friend_pics));
"SELECT * FROM fb_user WHERE find_in_set(user_id,'$friend_pics')     "

答案 1 :(得分:1)

为什么不将该数组转换为长值列表的字符串,除非数组是巨大的。

    $ids    = array(2, 4, 6, 8);
$params = implode(",", array_fill(0, count($ids), "?"));

    $result="SELECT * FROM fb_user WHERE user_id IN($params) ORDER BY oldscore DESC LIMIT 0,10";
db_execute($result);

答案 2 :(得分:1)

$friend_pics应该是一个包含逗号分隔列表的字符串,即“1,2,3,4”。如果不是,那么您的第二个查询将始终失败。