Article title is showing multiple times in foreach loop
Here is the 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>
And here is the functions.php code
<?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));
}
}
?>
Here is the screenshot of the output
The problem is within your loop. You are calling $articles["article_id"]
and $articles["article_title"]
. You want $article["article_id"]
and $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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.