我已经在这个简单的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
}
}
?>
答案 0 :(得分: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
。