我在名为ManageNews的类中使用此函数:
function getLatestNews($limit){
$query = $this->link->query("SELECT * FROM news ORDER BY date DESC LIMIT $limit");
$count = $query->rowCount();
if ($count !== 0){
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
return $row;
}
}
}
当我尝试从数据库获取新闻帖子的信息时,我将它们作为数组获取,我尝试了fetchAll(PDO::FETCH_ASSOC)
,但它将它们放在多维数组中,因此我无法使用{ {1}}因为他们不是[0],其余的都是[1] [2] [3]等......所以这就是我的做法:
$row[0]['column name'];
我正在$news = new ManageNews();
$row = $news->getLatestNews('5');
$article_id = $row['article_id'];
$user_id = $row['user_id'];
$title = $row['title'];
$content = $row['content'];
$date = $row['date'];
print_r($row);
$user = new ManageUsers();
$row2 = $user->getUserById($user_id);
if($row2 !== 1){
$user_name = $row2['username'];
$title2 = str_replace(" ","-",$title);
echo '<div class="row">
<div class="col-lg-12"><h3 class="para"><a class="para" href="http://news.red-sec.net/article/'.$article_id.'/'.$title2.'">'.$title.'</a></h3>
<p class="para">Written by: '.$user_name.'</p>
</div>
</div>';
}
查看数组。当它工作时它只是无限次打印最新的...我不知道为什么它做任何帮助赞赏
这就是现在的样子: http://prntscr.com/dz2b02
答案 0 :(得分:0)
就个人而言,我会使用一个发电机(只是为了保持基本功能与你已经编写的方式类似)
function getLatestNews($limit){
$query = $this->link->query("SELECT * FROM news ORDER BY date DESC LIMIT $limit");
$count = $query->rowCount();
if ($count !== 0){
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
yield $row;
}
}
}
答案 1 :(得分:-1)
我通过
修复了它while($row = fetchAll(PDO::FETCH_ASSOC)){
return $row;
}
在我做的文件中:
foreach($row as $r){do what i need to do}