PHP and MySQL Loop help? - php

Let's say I have a user that entered 12 links into the database but when they are displayed I want to break up the links into groups of 3 and repeat the groups of three until all 12 kinks are displayed for example.
<div>
<p>Link 1</p>
<p>Link 2</p>
<p>Link 3</p>
</div>
Here is part of the code I'm working with. How should my code look like?
while ($row = mysqli_fetch_assoc($dbc)) {
if (!empty($row['category']) && !empty($row['url'])) {
echo '<div>';
echo '<p>' . $row['category'] . '</p>';
echo '</div>';
}
}

Something like this gets you three links per div. We add the extra conditional echo at the end for the case that there's not a multiple of 3 links
$ctr = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
if (!empty($row['category']) && !empty($row['url'])) {
if ($ctr%3 == 0) {
echo '<div>';
}
$ctr ++;
echo '<p>' . $row['category'] . '</p?';
if ($ctr%3 == 0) {
echo '</div>';
}
}
}
if ($ctr%3 != 0) {
echo '</div>';
}

if you want to avoid incrementing/resetting i every time you reach three, you can just use the modulus operator:
http://php.net/manual/en/language.operators.arithmetic.php
Something like:
if( $i%3 == 0 ){
// divisible by 3...
}

An easier method would be more like:
while(true) {
$c = 0;
echo "<div>";
while ($row = mysqli_fetch_assoc($dbc) && $c++ < 3) {
if (!empty($row['category']) && !empty($row['url'])) {
echo '<p>' . $row['category'] . '</p>';
}
}
echo "</div>";
if(empty($row))
break;
}

Related

PHP Loop on every value on multidimensional array X times [duplicate]

I have a foreach statement in my app that echos a list of my database results:
<?php
foreach($featured_projects as $fp) {
echo '<div class="result">';
echo $fp['project_name'];
echo '</div>';
}
?>
I would like to:
On every third result, give the div a different class. How can I achieve this?
You can use a counter and the modulo/modulus operator as per below:
<?php
// control variable
$counter = 0;
foreach($featured_projects as $fp) {
// reset the variable
$class = '';
// on every third result, set the variable value
if(++$counter % 3 === 0) {
$class = ' third';
}
// your code with the variable that holds the desirable CSS class name
echo '<div class="result' . $class . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
<?php
foreach ($featured_projects as $i => $fp) {
echo '<div class="result' . ($i % 3 === 0 ? ' third' : '') . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
If the $featured_projects array is based on incremental index you could simply use the index and the modulo % operator.
Otherwise you would have to add a counter.
http://php.net/manual/en/language.operators.arithmetic.php
add a counter in this loop and check if counter equals three and apply class.
Using a counter and modulo operator this is easy to implement
<?php
foreach($featured_projects as $fp) {
if(++$i % 3 === 0) {
$class = ' something';
} else {
$class = '';
}
echo '<div class="result' . $class . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
<?php
$i = 0;
foreach($featured_projects as $fp) {
echo '<div class="'.($i++%3 ? 'result' : 'other_class').'">';
echo $fp['project_name'];
echo '</div>';
}
?>
What leaves your code mostly in tact would be
<?php
$i = 1;
foreach($featured_projects as $fp) {
printf ('<div class="%s">',(($i % 3) ? "result" : "result_every_third" ));
echo $fp['project_name'];
echo '</div>';
$i++;
}
?>
But you may want to consider using a for or while construct around "each($featured_projects)" (see http://php.net/manual/en/function.each.php) which may result in neater code.
<?php
$counter = 0;
foreach ($featured_projects as $fp) {
echo '<div class="result' . ($counter++ % 3 === 0 ? ' third' : '') . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
You can add a counter in loop ...try the following...
<?php
$i = 0;
foreach($featured_projects as $fp) {
$i = ++$i;
if(($i%3) == 0)
{
$class1 = 'test1';
}
else
{
$class1 = 'test2';
}
echo '<div class="'.$class1.'">';
echo $fp['project_name'];
echo '</div>';
}
?>
This is the working version, sorry for my prev version:
<?php
$featured_projects[0]['project_name'] = "pippo";
$featured_projects[1]['project_name'] = "pippo2";
$featured_projects[2]['project_name'] = "pippo3";
$class[0] = "class1";
$class[1] = "class2";
$i=0;
foreach($featured_projects as $fp) {
$i++;
if ($i == 3) {
$c = $class[1];
$i=0;
} else {
$c = $class[0];
}
echo "<div class=\"$c\">";
echo $fp['project_name'];
echo "</div>\n";
}
?>
Produces:
<div class="class1">pippo</div>
<div class="class1">pippo2</div>
<div class="class2">pippo3</div>

PHP - How to wrap every 2 items of a 'for' loop within a div

I'm looking for a way to wrap every too items of this very basic for loop within a div :
<?php
for( $i=1; $i<=50; $i++ )
{
echo "<div><a href='item-".$i."'>".$i."</a></div>";
}
?>
This produces the following :
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
The output i need would be :
<div>1 2</div>
<div>3 4</div>
Thanks
Easiest way i can think of is by doing this. This also works if you have a resultset from a database, or an array of item objects, just replace the range() function with the array.
<?php
foreach (array_chunk(range(1, 50), 2) as $chunk) {
echo "<div>";
foreach ($chunk as $itemId) {
echo "<a href='item-" . $itemId . "'>" . $itemId . "</a>";
}
echo "</div>" . PHP_EOL;
}
Use modulo operator
code:
<?php
$chunks = 2;
$display = true;
for( $i=1; $i<=6; $i++ )
{
if ($display && ($i % $chunks || $chunks === 1)) {
echo "<div>";
$display = false;
$last = true;
}
echo "<a href='item-".$i."'>".$i."</a>";
if (!($i % $chunks)) {
echo "</div>" . PHP_EOL;
$display = true;
$last = false;
}
}
if ($last) {
echo "</div>" . PHP_EOL;
}
generates:
<div><a href='item-1'>1</a><a href='item-2'>2</a></div>
<div><a href='item-3'>3</a><a href='item-4'>4</a></div>
<div><a href='item-5'>5</a><a href='item-6'>6</a></div>
and with:
$chunks = 3;
you will get:
<div><a href='item-1'>1</a><div><a href='item-2'>2</a><a href='item-3'>3</a></div>
<div><a href='item-4'>4</a><div><a href='item-5'>5</a><a href='item-6'>6</a></div>
and so one.

Count row and repeat the same rows within Loop

I'm working on mansory gallery here images fetching into the row first row contains three images and then for the second row contains two images and so on.
Now currently all images coming inside same row. I want to add in a loop I had tried but unable to achieve the result. For inspiration link
<?php
include('admin/config.php');
$result = mysqli_query($db, "SELECT * FROM gallery order by id desc");
// var_dump($result->num_rows);
while ($row = mysqli_fetch_array($result)) {
echo "<div class='gallery-items'>";
echo "<div class='mansory-item'>";
echo "<a href='admin/images/".$row['path']."' data-lightbox='gallery' class='ansa-thumb'>";
echo "<img src='admin/images/".$row['path']."' class='item-img img-1'>";
echo "</a>";
echo "</div>";
echo "</div>";
}
?>
Current output
Expected output
Can anyone suggest me how should i get this output.
Check below snippet,
$inc = 4;
$i = 1;
while ($row = mysqli_fetch_array($result)) {
if (empty($temp) || $inc != $temp) {
$temp = $inc;
if ($inc == 4) {
echo "<div class='gallery-grid'>";
}
echo "<div class='gallery-items'>";
}
if ($i <= $inc) {
// echo $i . '<>';
echo "<div class='mansory-item'>";
echo "<a href='admin/images/" . $row['username'] . "' data-lightbox='gallery' class='ansa-thumb'>";
echo "<img src='admin/images/" . $row['username'] . "' class='item-img img-1'>";
echo "</a>";
echo "</div>";
$i++;
}
if ($i == $inc) {
echo "</div>";
if ($i == 3) {
echo "</div>";
}
$i = 1;
$inc = ($inc == 4 ? 3 : 4);
}
}

PHP members page carrying down to new line

I have a page on my site that shows a member directory. I want the members to be listed 3 per row, before it goes to the next row. The code I have, does this for the very first row - but on the second row, its all on one line and doesnt carry down.
The profiles are showing up like this:
uuu
uuuuuuuuuuuuuuuuuuuuuuuuuuu
When they should be doing this:
uuu
uuu
uuu
uuu
This is what my code looks like:
<table>
<tr>
<td colspan="4"><h1>Member Directory</h1></td></tr>
<tr>
<td>
<?php
while($row = mysql_fetch_array($result)) {
if (empty($row['profile']) === false){
echo '<img src="', $row['profile'], ' "width="125">';
} else {
echo '<img src="../../images/template/avatar.png">';
}
echo '</td><td>';
echo '' . ucfirst($row['username']) . '<br />';
echo "Location: " . $row['location'] . "<br />";
echo '</td><td>';
if ($i++ == 2) echo '</td></tr><tr><td>';
}
?>
</td>
</tr>
</table>
Any help would be greatly appreciated, thanks!
Use
if (++$i % 3 == 0) echo '</td></tr><tr><td>';
Explanation:
First of all ++$i first increments $i, and then uses it in whatever is next, this makes for more readable code.
Second, the % is the modulus, which means it sortof subtracts 3 from $i until it is not possible anymore. E.g. 9 % 3 == 0, and 11 % 3 == 2 and so on. This means we know that we have printed 3 rows whenever $i % 3 equals 0.
try this one
<table>
<tr>
<td colspan="4"><h1>Member Directory</h1></td>
</tr>
<?php
$count=0;
while($row = mysql_fetch_array($result))
{
$count+=1;
if($count%3==1)
{
echo '<tr>';
}
echo '<td>';
if (empty($row['profile']) === false){
echo '<img src="', $row['profile'], ' "width="125">';
} else {
echo '<img src="../../images/template/avatar.png">';
}
echo '</td>';
echo '<td>';
echo '' . ucfirst($row['username']) . '<br />';
echo "Location: " . $row['location'] . "<br />";
echo '</td>';
if($count%3==0)
{
echo '</tr>';
}
}
if($count%3!=0)
{
echo '</tr>';
}
?>
</table>
You didn't reset the value of $i, so it kept increasing; another issue is that if you have only seven items, the last row should have four empty cells. So the loop condition needs to be augmented with a row completion status:
$i = 0;
while (($row = mysql_fetch_array($result)) !== false || $i != 0) {
if ($i == 0) {
echo '<tr>'; // start of new row
}
if ($row !== false) {
echo '<td>';
if (empty($row['profile'])) {
echo '<img src="', $row['profile'], ' "width="125">';
} else {
echo '<img src="../../images/template/avatar.png">';
}
echo '</td><td>';
echo '' . ucfirst($row['username']) . '<br />';
echo "Location: " . $row['location'];
echo '</td>';
} else {
echo '<td></td><td></td>'; // no more data
}
$i = ($i + 1) % 3; // advance
if ($i == 0) {
echo '</tr>'; // end of the row
}
}

How to show the value of two related arrays in php?

I have two arrays myarray1 has name of images and myarray2 has the address of images,
I am going to show image names and their addresses in pagination but do not know how to complete the code.
$pages = array_chunk($myarray1,10);
$addrs = array_chunk($myarray2,10);
$page_number = 1
$count = 0;
echo'<table>';
echo'<tr>';
foreach ($pages[$page_number] as $i) {
$counter++;
if ($count == 5) {
echo '</tr><tr>';
$counter = 0;
}
echo'<td>'.$i. " AND " . <<Value of addrs array goes here
echo'</td>';
}
.......
I'll do it on this way
$count = 1;
foreach ($pages[$page_number] as $key => $i) {
if ($count % 5 == 0) {
echo '</tr><tr>';
echo '</div>';
echo '</div>';
}
echo'<td>'.$i. " AND " . $addrs[$page_number][$key]
echo'</td>';
$count++; // increase at the end.
}
if you can try to var_dump those arrays before foreach just to be clear how structure looks like.
Try something like this: (note also the counter++ is changed in $count++)
foreach ($pages[$page_number] as $key => $i) {
$count++;
if ($count == 5) {
echo '</tr><tr>';
echo '</div>';
echo '</div>';
$count = 0;
}
echo'<td>'.$i. " AND " . $addrs[$page_number][$key]
echo'</td>';
}

Categories