Reputation: 309
I want to fetch two sets of data in a single query from MySQL using PHP. Below method fetch one row at a time but I want to fetch two rows at a time.
$qblog = "SELECT * FROM `blogs` WHERE status='1' ";
$qblog1 = mysqli_query($con,$qblog);
while($data = mysqli_fetch_array($qblog1)){
<div><?php echo $data['blog_title'];?></div>
<?php } ?>
Upvotes: 0
Views: 1345
Reputation: 39
This is not that hard if I understand correctly.
$sql = "select * from blogs where status = '1'";
$qblog1 = mysqli_query($con, $sql);
while ($row1 = mysqli_fetch_array($qblog1)) {
$row2 = mysqli_fetch_array($qblog1);
}
because you are reading from the same result set the pointer is updated just fine.
Upvotes: 0
Reputation: 1702
I'm not sure there is a way to get two rows at a time other than using LIMIT 2
in query. You can add some conditions to display two rows in a single iteration but in my point of view, you will need to add another loop inside while
like this one:
$qblog = "SELECT * FROM `blogs` WHERE status='1'";
$qblog1 = mysqli_query($con, $qblog);
$post_count = 0;
while($data = mysqli_fetch_array($qblog1)):
if($post_count === 2):
echo "<p>--------------------</p>";
foreach($data_temp as $data_tmp):
?>
<div><?php echo $data_tmp['blog_title'];?></div>
<?php
endforeach;
echo "<p>--------------------</p>";
$post_count = 0;
unset($data_temp);
endif;
$data_temp[] = $data;
$post_count += 1;
endwhile;
?>
I just had a look at https://www.homehero.org/blog which @Rajdeep Paul mentioned. It is about layout which means you can do it with CSS instead of going for conditions in PHP. Doing CSS way is a lot easier instead of making conditions in PHP.
Upvotes: 1
Reputation: 16963
From your comment,
... i want to show blogs like here, homehero.org/blog ,if you inspect element you will see 2 'blog-post' repeats in every 'rows'.
You have to use a counter variable to keep track of how many blog posts are being displayed on each row. So your code should be like this:
$qblog = "SELECT * FROM `blogs` WHERE status='1' ";
$qblog1 = mysqli_query($con,$qblog);
$counter = 1;
while($data = mysqli_fetch_array($qblog1)){
if($counter % 3 == 0){
// display the blogspots and style them
}
++$counter;
}
Upvotes: 1