div's with each 6 results in it PHP MYSQL - php

<div>
<?php if ($result->num_rows > 0) {
$i=1;
while($row = $result->fetch_assoc()) {
if( $i % 6 == 0 )
{ ?>
</div>
<div>
<?php } ?>
<h4><?php echo $row["city"] ?></h4>
<h6><?php echo $row["info"] ?></h6>
<?php $i++;
}
} else {
echo "0 results";
}
?>
</div>
Goal: div's with each 6 rows in it.
When I use $i=1, the first gets 5 results and the other ones get 6.
When I use $i=0 the first one is empty and the other ones get 6.
How to get the first div also filled with 6 results?

Try using array_chunk. That way you don't have to worry where to put your div ends and it's more readable:
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
foreach (array_chunk($rows, 6) as $subset) {
echo "<div>";
foreach ($subset as $row) {
echo "<h4>{$row["city"]}</h4>"
echo "<h6>{$row["info"]}</h6>"
}
echo "</div>";
}

Using array_chunk as proposed by #Justinas is a good way to refactor code. Yet, taking your original code, the issue is about where you check printed amount. It is wrong to first check output amount as it breaks the logic for the first iteration. Please, refer to the code below.
<div>
<?php
if ($result->num_rows > 0) {
$i = 1;
while ($row = $result->fetch_assoc()) {
# if ($i % 6 == 0) {
# echo '</div><div>';
# }
# move commented code from above to ...
echo "<h4>{$row["city"]}</h4>";
echo "<h6>{$row["info"]}</h6>";
# ... here
if ($i % 6 == 0) {
echo '</div><div>';
}
$i++;
}
} else {
echo "0 results";
}
?>
</div>

You can try setting $i = 0 then excluding it in your if statement with
if ($i > 0 && $i % 6 == 0)
since 0 % 6 == 0.

Related

Displaying array contents in pairs

I'm trying to make a website that displays all userprofiles. I want to wrap every two users in a <div>, until there is no left. So say we have 19 arrays consisting of userprofileinfo in $info - the following code will work fine, but will print out the 20th out as an empty div, which I want to prevent. What to do here?
$info = mysqli_fetch_all($result, MYSQLI_ASSOC);
for ($count = 0; $count <= mysqli_num_rows($result) - 1; $count += 2) {
echo <div class="row">
echo "<div>".print_r($info[$count])."</div>";
echo "<div>".print_r($info[$count+1])."</div>";ยจ
echo </div>
}
I think you might overthinking this. Why not simply use array_chunk()?
$info = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach (array_chunk($info, 2) as $chunk) {
echo '<div class="row">';
foreach ($chunk as $element) {
echo "<div>".$element['name']."</div>";
}
echo '</div>';
}
The way array_chunk() works is that it will group the array elements into chunks of a given size. You can have a double loop. The inner loop will iterate on each chunk and display both elements.
Just to provide a slightly cleaner version of Yvan1263's answer using OPs updated code (having fixed quotes).
$info = mysqli_fetch_all($result, MYSQLI_ASSOC);
for ($count = 0; $count <= count($info) - 1; $count += 2) {
echo '<div class="row">';
echo "<div>".print_r($info[$count])."</div>";
if (isset($info[$count+1])) {
echo "<div>".print_r($info[$count+1])."</div>";
}
echo </div>
}
You can just do this:
$info = mysqli_fetch_all($result, MYSQLI_ASSOC);
for ($count = 0; $count <= mysqli_num_rows($result); $count += 2) {
if($count+1 >= mysqli_num_rows($result)) {
/* IF MAX IS MORE THAN ENTRIES NUMBER */
echo "<div>".print_r($info[$count])."</div";
}
else {
echo "<div>".print_r($info[$count])."</div";
echo "<div>".print_r($info[$count+1])."</div";
}
}
NB: Use PDO instead of MySQLi.

How to echo every after 9th iteration of a loop? First echo only counted 8 items

My code is below:
function portfolio_gallery() {
global $conn;
$query = $conn->query("SELECT codename, namegroup, features, title, showimage FROM portfolio ORDER BY id DESC");
if ($query->num_rows > 0) {
// output data of each row
echo '<div>';
$i = 0;
while($row = $query->fetch_assoc()) {
$i++;
if ($row["showimage"]) {
if($i % 9 == 0){
echo '</div><div>';
}
echo '<a class="imgpop" href="images/portfolio/large/'.$row["codename"].'.jpg" rel="'.$row["namegroup"].'" title="'.$row["title"].' - '.$row["features"].'"><img src="images/portfolio/thumb/'.$row["codename"].'.jpg" alt="'.$row["title"].'" width="348"/><span class="imgpop-caption">'.$row["title"].'</span></a>';
}
}
echo '</div>';
}
}
portfolio_gallery();
I wanted to echo </div><div> for every after 9th item of the loop but every time I executed the code, the first echo only happened after 8 items instead of 9, but the rest was every 9th.
You have to increment
$i
after
if($i % 9 == 0)
follow the syntax example i worked out its working
<?php
$j=0;
for($i=0;$i<=50;$i++)
{
if($j==9)
{
echo $j.'hioiiiiiii<br/>'; //echo "</div><div>";
$j=-1;
}
$j++;
}
?>
Please try this :)
<?php
function portfolio_gallery() {
global $conn;
$query = $conn->query("SELECT codename, namegroup, features, title, showimage FROM portfolio ORDER BY id DESC");
if ($query->num_rows > 0) {
// output data of each row
echo '<div>';
$i = 0;
while($row = $query->fetch_assoc()) {
if ($row["showimage"]) {
if($i % 9 == 0){
echo '</div><div>';
}
echo '<a class="imgpop" href="images/portfolio/large/'.$row["codename"].'.jpg" rel="'.$row["namegroup"].'" title="'.$row["title"].' - '.$row["features"].'"><img src="images/portfolio/thumb/'.$row["codename"].'.jpg" alt="'.$row["title"].'" width="348"/><span class="imgpop-caption">'.$row["title"].'</span></a>';
}
$i++;
}
echo '</div>';
}
}
declare $i = 1 and Write $i++ at the end of while loop.
if ($query->num_rows > 0) {
// output data of each row
echo '<div>';
$i = 1; // declare $i = 1 here
while($row = $query->fetch_assoc()) {
if ($row["showimage"]) {
if($i % 9 == 1){ // 10 , 19 ,28
echo '</div><div>';
}
echo '<a class="imgpop" href="images/portfolio/large/'.$row["codename"].'.jpg" rel="'.$row["namegroup"].'" title="'.$row["title"].' - '.$row["features"].'"><img src="images/portfolio/thumb/'.$row["codename"].'.jpg" alt="'.$row["title"].'" width="348"/><span class="imgpop-caption">'.$row["title"].'</span></a>';
}
$i++; // increment at end of the loop
}
echo '</div>';
}
I was able to solve it by modifying the condition:
So instead of: if($i % 9 == 0) {...}
I used: if($i!=0 && $i % 9 == 0) {...}
And also placing $i++ at the end of while loop.

PHP Loop determine 4th iteration but if the iteration is less than 4 echo something

Heres the scenario, I have array with 7 items and I want to separate them in every fourth iteration.. just like this
$counter2 = 0;
$counter3 = 0;
$counter4 = 0;
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
foreach($sample_array as $sample_array_value)
{
if(++$counter4 % 4 == 0)
{
echo $sample_array_value;
echo "</div>";
}
elseif(++$counter3 % 3 == 0)
{
echo $sample_array_value;
}
elseif(++$counter2 % 2 == 0)
{
echo $sample_array_value;
}
else
{
echo "<div>";
echo $sample_array_value;
}
}
The out put will be div AsoPusaDagaKuting /div div TutaBubwitBoom
The problem is when it ends in iteration that doesn't count 4 it doesn't give the separator ending..
I need it to output div AsoPusaDagaKuting /div div TutaBubwitBoom /div
Thanks in advance...
You can split it with array_chunk, implode the new subarrays of 4 with array_map, then echo it with implode.
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
echo "<div>", implode("</div><div>", array_map("implode", array_chunk($sample_array, 4))), "</div>";
Result:
<div>AsoPusaDagaKuting</div><div>TutaBubwitBoom</div>
Try this:
$i = 0;
foreach($sample_array as $sample_array_value)
{
if(++$counter4 % 4 == 0)
{
echo $sample_array_value;
echo "</div>";
}
elseif(++$counter3 % 3 == 0 || ++$counter2 % 2 == 0)
{
echo $sample_array_value;
}
else
{
echo "<div>";
echo $sample_array_value;
}
$i++;
}
if ($i % 4 != 0) {
echo "</div>";
}
You are printing the values inside every condition, then why not use echo once outside any condition? Also you want to close and open a div tag for the forth element, then only 1 counter would do the trick. Only this will work -
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
$i = 0;
echo "<div>";
foreach($sample_array as $sample_array_value)
{
if($i > 0 && $i % 4 == 0)
{
echo "</div><div>";
}
echo $sample_array_value;
$i++;
}
echo "</div>";
Output
<div>AsoPusaDagaKuting</div><div>TutaBubwitBoom</div>

PHP For loop, how to loop code after 6 rows are displayed

So I am trying to wrap a div around my database results. The div must appear before first row and after the 6th row, it needs to close the div and loop it again. I tried to do it, but I can't manage to make it work properly. Any help would be appreciated.
for ($i=0; $i<count($row); $i++) {
if (($i) % 6 == 0) {
echo '<div class="swiper-slide">';
}
echo '<div class="col-lg-4 col-sm-6">
<img src="images/preview.jpg">
</div>';
if (($i) % 6 == 0) {
echo '</div>';
}
}
Also the code sample was not working at all (for/if/else not closed), see if this helps:
echo '<div class="swiper-slide">';
for ($i=0; $i<count($row); $i++)
{
if (($i>0) && ($i%6==0)) {
echo '</div>'."\n".'<div class="swiper-slide">';
}
echo '<div class="col-lg-4 col-sm-6"><img src="images/preview.jpg"></div>';
}
echo '</div>';
test at eval.in
try this
<div class="swiper-slide"><!-- open it using HTML out of <??> php tags-->
<?php
for ($i=0; $i<count($row); $i++) {
echo '<div class="col-lg-4 col-sm-6"><img src="images/preview.jpg"></div>';
if ($i % 6 == 0) {
//close and open new div for each group of 6
echo '</div>';
echo '<div class="swiper-slide">';
}//every 6th ... (you may need to change itto ( $i % 5 == 0)
}//for loop
echo '</div>';//close last opened, in case no more data or data less that 6
?>
Your second modulo operator compares the result to 9 instead of 0, and you have a } missing:
for ($i=0; $i<count($row); $i++) {
if (($i) % 6 == 0) {
echo '<div class="swiper-slide">';
}
echo '<div class="col-lg-4 col-sm-6"><img src="images/preview.jpg"></div>';
if (($i) % 6 == 0) { // Corrected 9 to 0
echo '</div>';
}
}
Try this:
foreach ($row as $key=>$result) {
if ($key==0 || $key == 5) { //If this is the first or sixth row.
echo '<div class="swiper-slide">';
}
echo '<div class="col-lg-4 col-sm-6"><img src="images/preview.jpg"></div>';
if ($key==0 || $key == 5) {
echo '</div>';
}
}

Execute code each time x <= y while looping

I'm not exactly sure how to explain this but basically I have an x variable equal to the number of rows in a database and each time it is equal to 4 or less, run a piece of code.
So say I have 5 rows, I want to execute the code twice because x is equal to 4 once and then equal to 1. Same if I had 6 rows (4+2) 7 rows (4+3) or 8 rows (4+4).
Then, when I reached 9 rows (4+4+1), it would execute the code thrice. Etc...
The code I'm trying to run is a piece of HTML with some more PHP inside it. I want to create a new <ul> with the said code inside it each time the number of rows is equal to 4 or less as explained above.
The code as it is right now:
<div class="row-fluid well">
<?php
$num_rows = mysql_num_rows($result);
if ($num_rows <= 4) {
?>
<ul class="minigames">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<li class='span3'>";
if (logged_in() === false && !empty($row['app_about']) === true && strlen($row['app_about']) <= 100) {
echo "<i class=\"icomoon-white icomoon-screen\"></i> Play in browser</center>'>";
} else if (logged_in() === false && !empty($row['app_about']) === true && strlen($row['app_about']) >= 101) {
$app_about = substr(strip_tags($row['app_about']), 0, 100);
echo "...<br /><br /><center><i class=\"icomoon-white icomoon-screen\"></i> Play in browser</center>'>";
} else if (!empty($row['app_about']) === true && strlen($row['app_about']) <= 100) {
echo "<i class=\"icomoon-white icomoon-screen\"></i> Play in browser</center>'>";
} else if (!empty($row['app_about']) === true && strlen($row['app_about']) >= 101) {
$app_about = substr(strip_tags($row['app_about']), 0, 100);
echo "...<br /><br /><center><i class=\"icomoon-white icomoon-screen\"></i> Play in browser</center>'>";
} else {
echo "<i class=\"icomoon-white icomoon-screen\"></i> Play in browser</center>'>";
}
?>
<img src="<?php echo $row['app_preview']; ?>">
<div class="minigames-caption">
<h4><?php echo $row['app_name']; ?></h4>
<p>By <?php echo $row['app_dev']; ?>.</p>
</div>
</a>
<?php
echo "</li>";
}
?>
<?php
}
?>
If the number of rows are limited, I would put the results into one array and then use array_chunk() to split them into portions.
$results = array();
while ($row = mysql_fetch_array($result)) {
$results[] = $row;
}
foreach (array_chunk($results, 4) as $chunk) {
echo '<ul>';
foreach ($chunk as $row) {
echo '<li>', /*....*/, '</li>';
}
echo '</ul>';
}
Divide x by 4 and round it up. Eg 4/4 = 1, 5/4 = 2, 9/4 = 3. Then, use a for loop.
var noOfTimes = //x/4 rounded up
for (var i = 0; i < noOfTimes; i++) {
//insert code here
}
Use the ceil function.
http://us3.php.net/manual/en/function.ceil.php
$num_rows = mysql_num_rows($result);
for ($i = 0; $i < ceil($num_rows / 4); $i++) {
// do stuff
}

Categories