文章标题在foreach循环中多次显示
这是articles.php
<?php
include('functions.php');
$article = new Article;
$articles = $article->fetch_all();
?>
<html>
<head>
<title>Sample Blog</title>
<link rel = "stylesheet" type = "text/css" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<div class="col-sm-6">
<h1 class="text-center">Articles</h1> </div>
<ol>
<?php
foreach($articles as $article){?>
<li>
<a href="article.php?id=<?php echo $articles["article_id"];?>">
<?php echo $articles["article_title"];?>
</a>
</li>
<?php
}
?>
</ol>
</div>
</body>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</html>
这是functions.php代码
<?php
require ('config.php');
if (!$connection) {
echo "Failed to connect to Server!".mysqli_connect_error();
}
class Article{
public function fetch_all(){
$connection = mysqli_connect(host,username,password,database) or die("Unable to connect to the host");
$select = "SELECT * FROM articles";
$result = mysqli_query($connection,$select) or die(mysqli_error($connection));
return (mysqli_fetch_assoc($result));
}
}
?>
这是输出的屏幕截图
答案 0 :(得分:2)
问题出在您的循环之内。您正在呼叫$articles["article_id"]
和$articles["article_title"]
。
您需要$article["article_id"]
和$article["article_title"]
。
foreach($articles as $article){?>
<li>
<a href="article.php?id=<?php echo $article["article_id"];?>">
<?php echo $article["article_title"];?>
</a>
</li>
<?php
}