PHP looping problem? - php

I have this script that displays a max of 5 images for each row, but for some reason my <ul> tag won't close correctly if the number of items isn't an exact multiple of 5. How can I correct this problem so the <ul> tag will close even if the number of listed images is less then 5?
Here is my PHP code.
if (!$dbc) {
print mysqli_error($mysqli);
} else {
$row_count = 0;
while($row = mysqli_fetch_array($dbc)){
if($row_count % 5 == 0){
echo "<ul>";
}
echo "<li><a href='" .$row["url"]. "' title='".$row['title']."'>";
echo "<img src='".$row['src']."'></a></li>";
if($row_count % 5 == 4) {
echo "</ul>";
}
$row_count++;
}
}

below the loop, check if
if (!$dbc) {
print mysqli_error($mysqli);
} else {
$row_count = 0;
while($row = mysqli_fetch_array($dbc)){
if($row_count % 5 == 0){
echo "<ul>";
}
echo "<li><a href='" .$row["url"]. "' title='".$row['title']."'>";
echo "<img src='".$row['src']."'></a></li>";
if($row_count % 5 == 4) {
echo "</ul>";
}
$row_count++;
}
if ( (($row_count % 5) > 0) && (($row_count % 5) < 4))
echo "</ul>";
}

$multiple = false;
if (!$dbc) {
print mysqli_error($mysqli);
} else {
$row_count = 0;
while($row = mysqli_fetch_array($dbc)){
if($row_count % 5 == 0){
echo "<ul>";
}
echo "<li><a href='" .$row["url"]. "' title='".$row['title']."'>";
echo "<img src='".$row['src']."'></a></li>";
if($row_count % 5 == 4) {
$multiple = true;
echo "</ul>";
} else {
$multiple = false;
}
$row_count++;
}
if($multiple == false) {
echo "</ul>";
}
}

if (!$dbc) {
print mysqli_error($mysqli);} else {
$row_count = 0;
//tank start
$total_rows = mysqli_num_rows($dbc);
//tank end
while($row = mysqli_fetch_array($dbc)){
if($row_count % 5 == 0){
echo "<ul>";
}
echo "<li><a href='" .$row["url"]. "' title='".$row['title']."'>";
echo "<img src='".$row['src']."'></a></li>";
//tank start
if($row_count % 5 == 4 || $row_count==$total_rows) {
//tank end
echo "</ul>";
}
$row_count++;
}

Here's my updated solution. I think it looks a little clearer. I do setup a few variables to get rid of some IF statements, and replace them with FOR loops. Mainly for readability and it's the way i thought of doing it.
$itemsperrow = 5;
$items = mysqli_num_rows($dbc);
$rows = $items / $itemsperrow;
$itemcount = 0;
if (!$dbc)
{
echo(mysqli_error($mysqli));
}
else
{
for ($int = 0; $int < $rows; $int++)
{
echo "<ul>";
for ($item = 0; $item < $itemsperrow; $item++)
{
if ($itemcount >= $items)
{
echo "</ul>";
exit;
}
else
{
$row = mysqli_fetch_array($dbc);
echo "<li><a href='". $row["url"] . "'>";
echo "<img src='" . $row["src"] . "' title='" . $row["title"] . "'/></a></li>";
$itemcount++;
}
}
echo "</ul>";
}
}

Related

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);
}
}

How do i use php to divide sql results into two columns if there are more than 8 results?

I have a footer on my website that has two links, by each other, that each can hold 8 links. How do i use php to divide the links into two sections but only if there are more than 8 results.This is what i have to display it right now.
<?php
$footer_sql = "SELECT title, link,widget FROM footer WHERE widget='1'";
$result = $db->query($footer_sql);
if ($result->num_rows > 0 AND $result->num_rows < 8) {
while($row = $result->fetch_assoc()) {
echo "<li><a href='".$row["link"]."'>". $row["title"] . "</a></li>";
}
elseif ($result->num_rows > 0 AND $result->num_rows > 8) {
//// This is where the thing would go to show 2 columns
}
} else {
echo "Error";
}
?>
<?php
// create array of your result
$footer_sql = "SELECT title, link,widget FROM footer WHERE widget='1'";
$result = $db->query($footer_sql);
if ($result->num_rows > 0)
$result = $result->fetch_assoc();
else
echo "Error";
//create array for both section
for($i=0;$i<count($result);$i++ )
{
if(i<8)
{
$section1[] = $result[$i];
}
else
{
$section2[] = $result[$i];
}
}
//now print to your html using foreach
foreach($section1 as $sec1)
{
//print in second col
echo "<li><a href='".$sec1["link"]."'>". $sec1["title"] . "</a></li>";
}
foreach($section2 as $sec2)
{
//print in second col
echo "<li><a href='".$sec2["link"]."'>". $sec2["title"] . "</a></li>";
}
?>

Take 10 array elements at a time in php?

echo "<table title='mxit:table:full' style='width: 100%' width='100%'><colgroup span='2' width='50%'></colgroup>";
foreach($arr['chart_data'] as $key => $element){
echo "<tr>";
foreach($element as $subkey => $subelement){
// $subelement =chop($subelement,'DIRECTSegment');
if($subkey++ < 2) {
if($key == 0)
{
echo "<td align='center;' style='color:white;'>$subelement</td>";
}
else if($subkey == 1)
{
echo "<td align='center;' style='color:white;'>$subelement</td>";
}
else
{
echo "<td align='center;' style='color:white;'><a href='getdata.php?key=$key'>".$subelement."</a></td>";
}
}
}
}
echo "</tr>";
echo "</table>";
How do i take only 10 elements of my array $arr['chart_data'] at a time ?
Set a counter, and then break the loop when $count hits 10.
$count = 0;
/* loop here */
if ($count == 10) break;
Anyway for all those who gave me negative votes and for my own betterment i solved my issue:
Here is what i did:
$totalfiles = count($arr['chart_data']);
$limit = 10;
$pages = ceil($totalfiles / $limit);
if (!isset($_GET['startrow']) or!is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int) $_GET['startrow'];
}
echo "<table title='mxit:table:full' style='width: 100%' width='100%'><colgroup span='2' width='50%'></colgroup>";
$data = array_slice($arr['chart_data'], $startrow, 10); // same as offset 0 limit 50 in sql
foreach($data as $key => $element) {
echo "<tr>";
foreach($element as $subkey => $subelement) {
$subelement = chop($subelement, 'DIRECTSegment');
if ($subkey++ < 2) {
if ($key == 0 && $startrow == 0) {
echo "<td align='center;' style='color:white;'>$subelement</td>";
} else if ($subkey == 1) {
echo "<td align='center;' style='color:white;'>$subelement</td>";
} else {
echo "<td align='center;' style='color:white;'><a href='getdata.php?key=$key'>".$subelement.
"</a></td>";
}
}
}
echo "</tr>";
}
echo "</table>";
/* free result set */
$result - > close();
}
/* close connection */
$mysqli - > close();
//now this is the link..
echo '<a href="'.$_SERVER['PHP_SELF'].
'?startrow='.($startrow + 10).
'">Next</a>';
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo ' <a href="'.$_SERVER['PHP_SELF'].
'?startrow='.$prev.
'">Previous</a>';
Implemented paging and using array slice to display 10 elements at a time.
Thanks for all the help

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>';
}

php mysql_fetch_array every 25 items wrap a div

I want to mysql_fetch_array 100 items from mysql database. then every 25 items wrap a div.
also, I make a total items result check.
My code as below, but it will add <div> to every item, no as my require. So how to make it easier? Thanks.
if (mysql_num_rows($result) != 0) {
$total = mysql_num_rows($result);
$num = 1;
while ($row = mysql_fetch_array($result)) {
if ($num === 1) {
echo '<div>';
}
echo $row['title'] . '<br />';
if ($total < 26) {
echo '</div>';
}
else {
if ($num === 26) {
echo '<div>';
}
if ($total < 51) {
echo '</div>';
}
else {
if ($num === 51) {
echo '<div>';
}
if ($total < 76) {
echo '</div>';
}
else {
if ($num === 75) {
echo '<div>';
}
if ($total < 101) {
echo '</div>';
}
}
}
}
$num++;
}
}
You can use the mod operator.
See: http://php.net/manual/en/internals2.opcodes.mod.php
echo '<div>';
while($row = mysql_fetch_array($result)){
....
if (($num % 25) === 1) { echo '</div><div>' }
$num++;
}
echo '</div>';
Try This...
if(mysql_num_rows($result)!=0){
$total = mysql_num_rows($result);
$num=1;
while($row = mysql_fetch_array($result)){
if($num===1)
echo '<div>';
echo $row['title'].'<br />';
if($num==25){
echo '</div>';
$num=1;
}
$num++;
}
}
use the mod operator.
$num =1;
while($row = mysql_fetch_array($result)){
if (($num % 25) === 1) { echo '<div>' }
-------here data ----
if (($num % 25) === 0) { echo '</div>' }
$num++;
}
My advice is to separate your concerns... Give it a shot more like this:
// first get all your data.
$results = array();
while($row = mysql_fetch_array($result)){
$results[] = $row;
}
// now you have an array of all of your records.
if (!empty($results)) {
// total count of the array up front.
$total = count($results);
$interval = 0;
// save the data in a buffer for echoing later.
$buffer = array('<div>');
foreach($results as $row) {
$buffer[] = $row['title'] . '<br />';
if (++$interval === 24) { // notice the prefix ++
$interval = 0;
// close and re-open divs
$buffer[] = '</div><div>';
}
}
// one final close tag
$buffer[] = '</div>';
// now we zip it up and echo the content.
echo implode('', $buffer);
}
Here is how I do it...
$count = 0;
while($row = mysql_fetch_array($result)){
if ($count%$25 == 0)
{
echo "<div>";
}
//whatever your data goes here
count++
if ($count%$25 == 0)
{
echo "</div>";
}
}

Categories