我的pdo查询似乎失败了,我不明白为什么

时间:2012-10-12 21:52:28

标签: php pdo

  

可能重复:
  PHP PDO bindValue in LIMIT

好的,这是我的疑问:

$db->sqlquery("
    SELECT a.*, c.`category_name`
    FROM `articles` a LEFT JOIN `articles_categorys` c
    ON c.`category_id` = a.`category_id`
    WHERE a.`active` = 1
    AND a.`category_id` IN (?)
    ORDER BY a.`date`
    DESC LIMIT ?", array($config['article_rss_categorys'], $limit)
);

我检查并设置了$config['article_rss_categorys'],其0,1,2,4,6,7$limit已设置,且15

这是我的查询代码

    try
    {
        $this->STH = $this->database->prepare($sql);

        foreach($objects as $k=>$p)
        {
            // +1 is needed as arrays start at 0 where as ? placeholders start at 1 in PDO
            if(is_numeric($p))
            {
                $this->STH->bindValue($k+1, $p, PDO::PARAM_INT);
            }
            else
            {
                $this->STH->bindValue($k+1, $p, PDO::PARAM_STR);
            }
        }

        return $this->STH->execute();

        $this->counter++;
    }

    catch (PDOException $e)
    {
        $core->message($e->getMessage());
    }

我不明白为什么会失败,我错过了一些愚蠢的东西吗?

我在phpmyadmin中测试了用正确的东西替换?的查询,它确实有用,所以数据库很好。

然后我尝试取出并输出结果;

while ($line = $db->fetch())
{
    // make date human readable
    $date = $core->format_date($line['date']);

    $output .= "
        <item>
            <title>{$line['category_name']} > {$line['title']}</title>
            <link>http://www.prxa.info/index.php?module=articles_comments&amp;aid={$line['article_id']}</link>
            <pubDate>{$date}</pubDate>
            <guid>http://www.prxa.info/index.php?module=articles_comments&amp;aid={$line['article_id']}</guid>
        </item>";
}

这是我的获取代码:

public function fetch()
{
    $this->STH->setFetchMode(PDO::FETCH_ASSOC); 
    return $this->STH->fetch();
}

1 个答案:

答案 0 :(得分:1)

据我所知,绑定参数只能表示单个值。你正试图这样做:

... WHERE foo IN (?) ...

然后绑定一个值数组(我假设),期望得到的查询看起来类似于:

... WHERE foo IN (1, 2, 3, ...) ...

那是不可能的。您需要在IN子句中尝试使用的值集中的每个值的参数:

... WHERE foo IN (?, ?, ?, ...) ...

修改

为了解释为什么你只返回一条记录 - 你将非数字值绑定为字符串,因此PHP会将数组转换为值为string(5) "Array"的字符串。然后将该字符串传递给数据库,并且可以将其转换为整数(因为这是数据库所期望的,并且大多数数据库的默认设置将键入强制)。这个字符串可能/可能被强制转换为整数0,从而产生如下查询:

... WHERE foo IN (0) ...

......显然导致难以追查的错误。