从db中选择数组中的所有项目?

时间:2013-06-14 15:25:30

标签: php pdo

我有一个如下所示的数组:(1,4,2,3)。 我想选择包含列tid的所有线程,其中包含数组中的一个数字:

$get = $pdo->prepare("SELECT * FROM mybb_threads ORDER BY replies DESC LIMIT 10");
$get->execute();                    
$array = $get->fetchAll(PDO::FETCH_COLUMN, 0);

$new = $pdo->prepare("SELECT * FROM mybb_posts WHERE replyto = 0 AND tid IN (:ids) LIMIT 10");
$new->execute(array(":ids" => implode(",", $array)));

但是,它只从数据库中提取一个项目,而我有多个结果?

为什么这样做?

我认为它只取出第一个数组项目,我不确定,但你看错了吗?

我想做的是:

我有标签。

选项卡通过回复显示最受欢迎的主题。 我想这样做,当你点击标签时,它会切换到右边的帖子。

<div class="container row">
    <h2>Top 10 Stories</h2>
    <div id="story-tab">
        <ul>
            <?php
            $test = $pdo->prepare("SELECT * FROM mybb_threads ORDER BY replies DESC LIMIT 10");
            $test->execute();

        //  while ($row = $test->fetch(PDO::FETCH_ASSOC))
            //{
                //echo'<li><a href="#st-'.$row['tid'].'-'.$row['fid'].'">'. $row['subject'].'</a></li>';
                echo'<li><a href="#st-1-1">1</a></li>';
                echo'<li><a href="#st-2-1">2</a></li>';
            //} 
            $get = $pdo->prepare("SELECT * FROM mybb_threads ORDER BY replies DESC LIMIT 10");
            $get->execute();                    
            $array = $get->fetchAll(PDO::FETCH_COLUMN, 0);

            ?>
        </ul>
        <?php
            $test = $pdo->prepare("SELECT * FROM mybb_threads ORDER BY replies DESC");
            $test->execute();

            $fetch = $test->fetch(PDO::FETCH_ASSOC);

            $new = $pdo->prepare("SELECT * FROM mybb_posts WHERE replyto = 0 AND tid IN (:ids) LIMIT 10");
            $new->execute(array(":ids" => implode(",", $array)));

            while ($row = $new->fetch(PDO::FETCH_ASSOC))
            {
                echo '<br /><br /><br /><br />'. $row['tid'].','.$row['fid'];
            }
        ?>
    </div>
    <br class="clear">
    <h2>Top 10 Popular Threads</h2>
    <div id="thread-tab">

    </div>
</div>

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

就在http://php.net/manual/en/pdostatement.execute.php 示例#5 ,演示了如何使用int数组准备带有IN子句的语句。对于你的情况,它将是......

$params = array(1, 21, 63, 171);
/* Create a string for the parameter placeholders filled to the number of params */
$place_holders = implode(',', array_fill(0, count($params), '?'));

$sth = $dbh->prepare("SELECT * FROM mybb_posts WHERE replyto = 0 AND tid IN ($place_holders) LIMIT 10"); 
$sth->execute($params); // fills the placeholder ?'s with the values of your array

希望这有帮助。

答案 1 :(得分:0)

而不是..

$new->execute(array(":ids" => implode(",", $array)));
你可以试试吗

$ins= implode(',', array_fill(0, count($array), '?'));

然后

$new->prepare("SELECT *  FROM mybb_posts WHERE replyto =0 AND tid IN ($ins) LIMIT 10");
$new->execute($ins);