SELECT WHERE IN不检索所有记录

时间:2013-04-16 17:37:11

标签: php mysql pdo in-clause

编辑: 澄清一下,我正在使用PDO到MySQL数据库

好的,我的查询有点问题。我试过谷歌搜索和'stackoverflowing',无济于事。 我正在尝试从名为 download store 的表中选择所有记录,其中ownerid ='1'

//Partial code
 $sql="SELECT * FROM boughtdownloads WHERE ownerid=:userid";
 $prep=$GlobalDB->prepare($sql);
 $prep->bindParam(':userid',$userid,PDO::PARAM_INT);
 $prep->execute();
 if($prep->rowCount()=='0')
 {
   return 'Error with get owned IDS';
 }
 else
 {
   foreach($prep->fetchAll()as $res)
   {
      $owned[]=$res['fileid'];
   }
    $owned=implode(",",$owned);
    return $owned;
 }

按预期工作,返回 1,2

$OwnedIDS=$this->GetOwnedIDS($userid); // The same code as above ^
//This query doesn't work, even with the following:
//$OwnedIDS="1,2"; //Which is what's expected, and returned, from the above
$sql="SELECT * FROM downloadstore WHERE fileid IN (:owned)";
$prep=$GlobalDB->prepare($sql);
$prep->bindParam(':owned',$OwnedIDS);
$prep->execute();
if($prep->rowCount()=="0")
{
   return 'Error with remaining disk space';
}
 else
{
  echo $prep->rowCount();
}

这只返回1条记录,尽管 downloadstore表中有两条记录 $GlobalDB = pdo连接字符串(有效)

$userid = $_SESSION,等于“1”

[下载商店截图] DownloadStore Table

[BoughtItems screenshot]

BoughtItems Table

如您所见,每个表中有2条记录,带有有效的fileid。

但是当使用IN子句查询下载商店时,只会拉出1条记录。

有人可以帮帮我吗? 这可能是我忽略的简单傻事,但我已经三次检查了,我确信我的查询或表格没有任何错误(尽管很明显)。

谢谢, 罗布

2 个答案:

答案 0 :(得分:2)

您需要为数组的每个元素创建一个bind参数,然后绑定每个元素:

$bindParams = array();
foreach ($ownerIds as $index => $ownerId) {
    $bindParams[] = ':ownerId' . $index;
}

$sql = 'select * from downloadstore where fileid in (' . implode(', ', $bindParams) . ')';
$prep = $db->prepare($sql);

foreach ($ownerIds as $index => $ownerId) {
    $prep->bindValue(':ownerId' . $index, $ownerId);
}

答案 1 :(得分:0)

MySQL中,您无法绑定IN列表。

您应该在客户端上解析它并将其传递给查询文本,而不是在绑定变量中传递:

# sanity checks for $ownerIds go here
$sql="SELECT * FROM downloadstore WHERE fileid IN (" . implode(',', $ownerIds) . ")";

或者,最好,您可以在服务器端执行所有操作:

SELECT  ds.*
FROM    boughtdownloads bd
JOIN    downloadstore ds
ON      ds.fileId = bd.fileId
WHERE   bd.ownerId = :userId