1

几个小时以来,我一直在研究这个简单的 PDO 查询。从 MySQL 多个数据库中获取此类信息的正确方法是什么。在这个查询中应该使用 Fetch 还是 FetchAll?因为它正在查询多个数据库。

下面是我尝试将已弃用的 MySQL 转换为 PDO。

mysql。

    public function Comments($post_iD) {
        $query = mysql_query("
                                SELECT C.com_id, C.uid_fk, C.comment, C.created, U.username 
                                FROM comments C, users U 
                                WHERE U.status = '1' 
                                AND C.uid_fk = U.uiD 
                                AND C.msg_id_fk = '$msg_id'
                                ORDER by C.com_id"); or die(mysql_error());

            while( $row = mysql_fetch_array($query) )
                $data[] = $row;
            if( !empty( $data ) ){
                return $data;
            }
    }

PDO:

    PUBLIC FUNCTION Comments( $post_iD ){
        $sth = $this->db->prepare("
                                SELECT C.com_id, C.uid_fk, C.comment, C.created, U.username 
                                FROM comments C, users U 
                                WHERE U.status = '1' 
                                AND C.uid_fk = U.uiD 
                                AND C.msg_id_fk = ?
                                ORDER by C.com_id");

        $sth->execute(array($post_iD));

        $data = $this->fetch();
        return $data;
        }
    }

这就是我显示数据库的方式。

    <?php   
        $commentsarray = $Wall->Comments( $post_iD );

        if( $commentsarray ){
            foreach($commentsarray as $data){
                $com_id     =   $data['com_id'];
                $comment    =   tolink(htmlcode($data['comment'] ));
                $time       =   $data['created'];
                $mtime      =   date("c", $time);
                $username   =   $data['username'];
                $com_uid    =   $data['uid_fk'];
                $cface      =   $Wall->Profile_Pic($com_uid);
    ?>
                <div class="stcommentbody" id="stcommentbody<?php echo $com_id; ?>">
                    <div class="stcommentimg">
                        <img src="<?php echo $cface;?>" class="small_face" alt=<?php echo $username;?>">
                    </div> 

                    <div class="stcommenttext">
                        <?php echo clear($comment); ?>
                    </div>
            </div>
<?php
        } 
    }
?>
4

1 回答 1

3

您想要(fetchAll()在您的查询中使用$sth

$data = $sth->fetchAll();

而不是(fetch()在您的数据库连接上$this->

$data = $this->fetch();

作为 哪里。
fetch() Fetches the next row from a result set

fetchAll() Returns an array containing all of the result set rows

于 2013-06-26T00:32:44.473 回答