我想在index.php上列出一个带有一个查询和foreach函数的多篇文章。
但我不知道是否可能,你们能告诉我一个如何做到的例子吗?
我可以这样做,但在所有方框中显示相同的帖子,我想在每个方框中显示不同的帖子。
抱歉我的英语不好:(
示例:
<?php
include("header.php");
/* Slider */
$query = $db->read_query("SELECT id, title, spot, image, date, cuff, type
FROM news
WHERE active = 'Y'
AND cuff_view = 'Y'
ORDER BY date DESC
LIMIT 10") or die($db->sql_error());
$HeadNews = array();
while($row = $db->sql_fetcharray($query)){
$HeadNews[] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Posts</title>
</head>
<body>
**// first article box**
<h1>fruits</h1>
<ul>
<?php
foreach($HeadNews as $k=>$news){
$news_url_seo = $news[id]."-".seo($news[title]).".html";
?>
<li><?php echo stripslashes($news[image]);?>" width="350" /></li>
<li><p><?=stripslashes($news[spot])?>.</p>
<a href="<?=$news_url_seo;?>">Details</a></li>
<?php } ?>
</ul>
**// second article box**
<h1>fruits 2</h1>
<ul>
<?php
foreach($HeadNews as $k=>$news){
$news_url_seo = $news[id]."-".seo($news[title]).".html";
?>
<li><?php echo stripslashes($news[image]);?>" width="350" /></li>
<li><p><?=stripslashes($news[spot])?>.</p>
<a href="<?=$news_url_seo;?>">Details</a></li>
<?php } ?>
</ul>
**// Third article box**
<h1>fruits 3</h1>
<ul>
<?php
foreach($HeadNews as $k=>$news){
$news_url_seo = $news[id]."-".seo($news[title]).".html";
?>
<li><?php echo stripslashes($news[image]);?>" width="350" /></li>
<li><p><?=stripslashes($news[spot])?>.</p>
<a href="<?=$news_url_seo;?>">Details</a></li>
<?php } ?>
</ul>
</body>
</html>
答案 0 :(得分:1)
我没有测试过我的答案,但这应该给你一个基本的想法。 我希望您通过查看此代码了解如何使用foreach循环。
<?php
include("header.php");
/* Slider */
$query = $db->read_query("SELECT id, title, spot, image, date, cuff, type
FROM news
WHERE active = 'Y'
AND cuff_view = 'Y'
ORDER BY date DESC
LIMIT 10") or die($db->sql_error());
$HeadNews = array();
while($row = $db->sql_fetcharray($query)){
//Populate the array
$HeadNews[$row[id]] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Posts</title>
</head>
<body>
**// Create all article boxes**
<?php
foreach($HeadNews as $k=>$news){
//For each item in the array, create an article box
$news_url_seo = $news[id]."-".seo($news[title]).".html";
?>
<h1>fruits <?php echo $k ?></h1>
<ul>
<li><?php echo stripslashes($news[image]);?>" width="350" /></li>
<li><p><?=stripslashes($news[spot])?>.</p>
<a href="<?=$news_url_seo;?>">Details</a></li>
</ul>
<?php } ?>
</body>
</html>