I am trying to fetch post data from MySQL database. I have used while loop for fetching rows from the table. I have five rows in my MySQL database. But it is fetching rows until my browser crashes. Why is it happening? How to solve this problem?
This is the main code:
<div class="container clearFix">
<?php
while ($result = Data::fetch_table('posts')) {
?>
<div class="post">
<div class="post-title">
<h2><?php echo $result['title'];?></h2>
</div>
<div class="date">
Published on: <?php echo $result['post_date'];?>
</div>
<div class="post-body">
<?php echo $result['body'];?>
</div>
<div class="read-more">
<a href="sh07/post.php?id=<?php echo $result['id'];?>">Read More</a>
</div>
</div>
<?php
}
?>
</div>
And here is the Data Class code:
class Data {
public static function fetch_table($table_name) {
// Connection variables
$con = new Database;
$con = $con->connection();
// SQL Queries
$sql = "SELECT * FROM $table_name";
$result = $con->query($sql);
return $result->fetch_assoc();
}
Note: The database connection is already established in Data Class .
Thanks for your any help.
When you call fetch_table
you connect to the database, make a query, and return the first result.
Your while loop keeps going until it doesn't get a result … which will never happen because you always start from a new connection and give it the first result.
You need to connect to the database once , make the query once , and then repeatedly call only fetch_assoc
until you run out of rows.
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.