Execute code each time x <= y while looping - php

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
}

Related

PHP while loop separate from every 2 rows into a div

I have a while loop from database, but i want to wrap every 2 rows into a div.
Currently i have this but is only wrapping first row.
<?php
$get = $connect->query("SELECT * FROM sabiaque ORDER by ordem");
$num = 0;
while ($f = $get->fetch_array(MYSQLI_ASSOC)) {
if ($num % 2) {
echo '<div class="divisor-slide">';
}
echo'
<a href="'.$f['link'].'"><div class="item-a">
<div class="box1-item-a">
<div class="i-wrap"><h1 class="i-white">'.utf8_decode($f['titulo']).'</h1><p>'.utf8_decode($f['subtitulo']).'</p></div>
</div>
<div class="box1-item-b">
<img src="../'.$f['ficheiro'].'" style="max-width: 100%; height: 100%;" />
</div>
</div></a>
';
if($num % 2) {
echo '</div>';
}
$num++;
}
?>
change this :
if($num%2) {
echo '<div class="divisor-slide">';
}
By this :
if( ($num % 2) == 0) {
echo '<div class="divisor-slide">';
}
And this :
if($num %2) {
echo '</div>';
}
To :
if( ($num % 2) == 0) {
echo '</div>';
}
I often find I get into a muddle using these special $num%2 whatsits (I'll get all excited in being clever in using them, then forget later what they do when I revisit the code). Why not simplify it like this (although it uses a little more code):
$num = 1;
while ($f = $get->fetch_array(MYSQLI_ASSOC)) {
if ( $num == 2 ) echo '<div class="divisor-slide">';
// rest of code
if ( $num == 2 ) echo '</div>';
$num++; if ( $num == 3 ) $num = 1;
}

div's with each 6 results in it PHP MYSQL

<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.

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.

Split query results in 2 div's

i have this php mysql query
<?php
$product = mysql_query('SELECT * FROM products LIMIT 6 ');
$pro = mysql_fetch_assoc($product);
?>
Now that query will return 6 products from database and what i want to do is echo 3 products inside a <div> and the other 3 products inside another <div> like this
<div class="first-3>
///Here i want to echo 3 products from the query from 1-3
<?php echo $pro['title']; ?>
</div>
<div class="second-3>
///Here i want to echo the rest 3 products of the query from 4-6
<?php echo $pro['title']; ?>
</div>
<?php
$num = 6;
$product = mysql_query('SELECT * FROM products LIMIT $num');
$firstDiv = "";
$secondDiv = "";
$i = 0;
while ($pro = mysql_fetch_assoc($product)) {
if ($i < ($num /2)) {
$firstDiv .= $pro['title'];
}
else {
$secondDiv .= $pro['title'];
}
$i++;
}
?>
And:
<div class="first-3>
<?php $firstDiv ?>
</div>
<div class="second-3>
<?php $secondDiv ?>
</div>
Iterate and output the values.
<?php
$product = mysql_query('SELECT * FROM products LIMIT 6 ');
$i = 1;
echo '<div class="first-3">';
while ( $pro = mysql_fetch_assoc($product) ) {
if ($i === 3) {
echo '</div><div class="second-3">';
}
echo $pro['title'];
$i++;
}
echo '</div>';
?>
Note that it's not safe to use mysql_query, you should be using mysqli or preferrably PDO.
mysql_fetch_assoc is used to retrieve a row in the resultset.
Doc: http://php.net/manual/es/function.mysql-fetch-assoc.php
A loop is required to iterate on each row.
A very simple example:
// Get a collection of 6 results
$products = mysql_query('SELECT * FROM products LIMIT 6 ');
// iterate over the 6 results
$i=0;
echo '<div class="first-3>';
while ($pro = mysql_fetch_assoc($products)) {
$i++;
// Print an item
echo $pro["title"];
// If 3 items are printed end first div and start second div
if($i==3){
echo '</div><div class="second-3">';
}
}
echo '</div>';
// Free the collection resources
mysql_free_result($products);
Just set up a counter to divide in groups of 3:
$count = 0;
while (...)
{
// your code
$count++;
if ( ($count % 3) === 0 )
{
echo '</div><div class="...">';
}
}
Please note that the mysql_* functions are deprecated and you should switch to PDO or mysqli.
$product = mysqli_query($conn, 'SELECT * FROM products LIMIT 6 ');
$results = array();
while($pro = mysqli_fetch_assoc($product)) {
$results[] = $pro;
}
echo '<div class="first-3">';
for($i = 0; $i < 3; $i++) {
echo $results[$i]['title'];
}
echo '</div><div class="second-3">';
for($i = 3; $i < 6; $i++) {
echo $results[$i]['title'];
}
echo '</div>';
Everytime you get the multiple of 3, ($k % 3 == 0) you will increment the flag variable, you can do then some conditions with the variable flag, i used here iterators because the hasNext() beauty.
Example
$pro = array(1, 2, 3, 4, 5, 6);
$flag = 0;
$pro = new CachingIterator(new ArrayIterator($pro));
foreach ($pro as $k => $v) {
// if multiples 3
if ($k % 3 == 0) {
$flag++;
if ($flag == 1) {
echo '<div class="first-3" style="border:1px solid black;margin-bottom:10px;">';
} else if ($flag == 2) {
echo '</div>'; // Closes the first div
echo '<div class="second-3" style="border:1px solid red">';
}else{ // if you have more than 6
echo '</div>';
}
}
// insert Data
echo $v . '<br/>';
if (!$pro->hasNext())
echo '</div>'; // if there is no more closes the div
}

Merging Code with Display on Loop

Trying to create DIV containers out of a mysql results which each hold chunks of 10.
$balloon_count = the amount of records each div should hold.
$ui = the loop counter.
Functionality is simple, don't want to a template engine.
Trying to use the MODULUS operator to simplify the div cuts.
Doesn't work. Any direction is greatly appreciated.
Sample Code
$ui=1;
$balloon_holds = 10;
while($row = mysql_fetch_array($result))
{
if($ui==1||$ui%$balloon_holds != 0)
{
echo '<div><table style="width:400px;border:2px solid gray;border-style:dashed;"><tr>';
echo "<td style=\"font-size:small;vertical-align:text-top;\">";
}
echo '<input disabled type="checkbox" value="$row[id]"'; $this->ischecked($uid,$row[id]); echo "/>".$row['name'].'<br>'."\r\n";
if($ui==10||$ui%$balloon_holds != 0){
echo '</td></tr></table></div>';
}
$ui++;
}
Sample Expected "HTML" Output
<div><table style="width:400px;border:2px solid gray;border-style:dashed;"><tr>
<td style="font-size:small;vertical-align:text-top;">
Record1
Record2
Record3
Record4
Record5
Record6
Record7
Record8
Record9
Record10
</td></tr></table></div>
<div><table style="width:400px;border:2px solid gray;border-style:dashed;"><tr>
<td style="font-size:small;vertical-align:text-top;">
Record11
Record12
Record13
Record14
Record15
Record16
Record17
Record18
Record19
Record20
</td></tr></table></div>
If I understand the question correctly, you want the <div> opener on $ui = 1,11,21,31,... and the </div> closer on 10,20,30,40,...
If this is correct, your modulus operators should be changed as such:
if($ui%$balloon_holds == 1)
{
...
}
...
if($ui%$balloon_holds == 0)
{
...
}
if($ui==1||$ui%$balloon_holds != 0)
This will always be true except for when $ui is a multiple of 10, so you'd be outputting your header/footer blocks for ALL rows except 0, 10, 20, etc... and the one case where $ui is 1.
Most like likely this would be easier to understand:
$row_cnt = 0;
$max_rows = 10;
while($row = ...) {
if ($row_cnt == 0) {
// output header
}
// output row data
if ($row_cnt == 9) {
// output row footer
}
$row_cnt++;
$row_cnt %= $max_rows; // ($row_cnt resets to 0 when it reaches 10)
}
Here is my suggestion, it's also a little more readable / maintainable.
$ui=0;
$balloon_holds = 10;
while ($row = mysql_fetch_array($result))
{
if ($ui % $balloon_holds)
{
if ($ui >= 10)
{
echo '</td></tr></table></div>';
}
echo '<div><table style="width:400px;border:2px solid gray;border-style:dashed;"><tr>';
echo "<td style=\"font-size:small;vertical-align:text-top;\">";
}
echo '<input disabled type="checkbox" value="$row[id]"';
$this->ischecked($uid,$row[id]);
echo "/>".$row['name'].'<br>'."\r\n";
$ui++;
}
if ($ui > 0)
{
echo '</td></tr></table></div>';
}
$ui=0;
$balloon_holds = 10;
while($row = mysql_fetch_array($result))
{
$exit = 0;
if($ui==1||$ui%$balloon_holds != 0)
{
echo '<div><table style="width:400px;border:2px solid gray;border-style:dashed;"><tr>';
echo "<td style=\"font-size:small;vertical-align:text-top;\">";
}
echo '<input disabled type="checkbox" value="$row[id]"'; $this->ischecked($uid,$row[id]); echo "/>".$row['name'].'<br>'."\r\n";
$ui++;
if($ui%$balloon_holds == 0){
echo '</td></tr></table></div>';
$exit = 1;
}
}
if($exit == false){
echo '</td></tr></table></div>';
}

Categories