Split PHP loop into 2 lists - php

I have built the following function, but is it possible to get it to split my lists from one into more so I can have a maximum of 8 <li>'s per <ul>?
function buildProductsMenu($base) {
$sql = "SELECT *
FROM tbl_category";
$result = dbQuery($sql);
while ($row = dbFetchAssoc($result)) {
echo "<ul>";
echo "<li class='title'>$row[cat_name]</li>";
$sqlProd = "SELECT *
FROM tbl_product WHERE cat_id = $row[cat_id]";
$resultProd = dbQuery($sqlProd);
while ($rowProd = dbFetchAssoc($resultProd)) {
extract($rowProd);
echo "<li><a href='".$base."products/".strtolower($row['cat_name'])."/".strtolower($pd_name)."'>".$pd_name."</a></li>";
}
echo "</ul>";
}
}
Went with jurgemaister Solution
function buildProductsMenu($base) {
$sql = "SELECT *
FROM tbl_category";
$result = dbQuery($sql);
while ($row = dbFetchAssoc($result)) {
echo "<ul>";
echo "<li class='title'>$row[cat_name]</li>";
$sqlProd = "SELECT * FROM tbl_product WHERE cat_id = $row[cat_id]";
$resultProd = dbQuery($sqlProd);
$counter = 1;
while ($rowProd = dbFetchAssoc($resultProd)) {
extract($rowProd);
if($counter % 12 == 0) {
$counter = 1;
echo "</ul><ul style='margin-top:25px;'>";
}
echo "<li><a href='".$base."products/".strtolower($row['cat_name'])."/".strtolower($pd_name)."'>".$pd_name."</a></li>";
$counter++;
}
echo "</ul>";
}
}

You can add a counter, and when that counter reaches 8, you start a new ul.
$counter = 1;
while ($rowProd = dbFetchAssoc($resultProd)) {
extract($rowProd);
if($counter % 8 == 0) {
$counter = 1;
echo "</ul><ul>";
}
echo "<li><a href='".$base."products/".strtolower($row['cat_name'])."/".strtolower($pd_name)."'>".$pd_name."</a></li>";
counter++;
}

Okay, instead of echoing the LIs right from the function I suggest you add them all to an array, once things are in an array, its always easier to manage.
Use array_chunk() on the final array of LIs and it will split it into groups of eight.

Related

PHP Pagination for MySQL posts

I've been trying for hours to implement a pagination for a blog that I am working on, but I just can't find it to work. In the URL, it gives me (myurl).php?pageno=
Without the page number requested.
This is my page to handle the database request:
<?php
require_once("db-connect.php");
$offset = 0;
$page_result = 5;
if($_GET['pageno'])
{
$page_value = $_GET['pageno'];
if($page_value > 1)
{
$offset = ($page_value - 1) * $page_result;
}
}
$results = mysqli_query($connection, "SELECT * FROM blog where $condition ORDER BY date DESC LIMIT $offset, $page_result")
or die(mysqli_error('No Records Found'));
?>
This is my blog page code:
<?php
if (mysqli_num_rows($results) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($results)) {
echo "<li class='background-white'><div class='column large-4'><a href='".$row['link']."' class='text-black1' title='".$row["arttitle"]."'>"."<img src='http://tmggeotech.com/img/blog/".$row['thumbnail']."' alt='".$row['thumbalt']."'/>"."</a></div>"."<div class='column large-8 article-data'>"."<h4><a href='".$row['link']."' class='text-black1' title='".$row["arttitle"]."'>".$row["arttitle"]."</a></h4>"."<small class='text-black2'>Publicado el <span class='text-orange2'>".date('m/d/Y', strtotime($row['date']))."</span> | "."Categoría: <span class='text-orange2'>".$row["category"]."</span></small>"."<p>".$row["excerpt"]."</p>"."</div>"."</li>";
} }else {
echo "0 results";
}
$pagecount = 50; // Total number of rows
$num = $pagecount / $page_result;
if($_GET['pageno'] > 1) {
echo "Prev";
}
for($i = 1 ; $i <= $num ; $i++) {
echo "".$i."";
}
if($num != 1) {
echo "Next";
}
?>
So my question is:
Is it there something I am missing here to make it work?
Thanks to #ccKep for point out some clues on how to get what I needed. I just made it work.
In page to handle the database request, I added a second request but without LIMIT, so that I could use num_rows with it:
<?php
require_once("db-connect.php");
$offset = 0;
$page_result = 5;
if($_GET['pageno'])
{
$page_value = $_GET['pageno'];
if($page_value > 1)
{
$offset = ($page_value - 1) * $page_result;
}
}
$results = mysqli_query($connection, "SELECT * FROM blog where $condition ORDER BY date DESC LIMIT $offset, $page_result")
or die(mysqli_error('No Records Found'));
$npages = mysqli_query($connection, "SELECT * FROM blog where $condition ORDER BY date DESC")
or die(mysqli_error('No Records Found'));
?>
Later, on my blog page I round up my posts to the next multiple of 5 number.
And also changed my last if statement so that the NEXT button disappears after getting the last page.
<?php
if (mysqli_num_rows($results) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($results)) {
echo "<li class='background-white'><div class='column large-4'><a href='".$row['link']."' class='text-black1' title='".$row["arttitle"]."'>"."<img src='http://tmggeotech.com/img/blog/".$row['thumbnail']."' alt='".$row['thumbalt']."'/>"."</a></div>"."<div class='column large-8 article-data'>"."<h4><a href='".$row['link']."' class='text-black1' title='".$row["arttitle"]."'>".$row["arttitle"]."</a></h4>"."<small class='text-black2'>Publicado el <span class='text-orange2'>".date('m/d/Y', strtotime($row['date']))."</span> | "."Categoría: <span class='text-orange2'>".$row["category"]."</span></small>"."<p>".$row["excerpt"]."</p>"."</div>"."</li>";
} }else {
echo "0 results";
}
$x = ceil($npages->num_rows/5) * 5;
$pagecount = $x; // Total number of rows
$num = $pagecount / $page_result;
if($_GET['pageno'] > 1) {
echo "<a href='noticias-perforacion-suelos-articulos-maquinas-blog.php?pageno=".($_GET["pageno"] - 1)."'>Prev</a>";
}
for($i = 1 ; $i <= $num ; $i++) {
echo "<a href='noticias-perforacion-suelos-articulos-maquinas-blog.php?pageno=".$i."'>".$i."</a>";
}
if($_GET['pageno'] == $num) {
echo "";
} else {
echo "<a href='noticias-perforacion-suelos-articulos-maquinas-blog.php?pageno=".($_GET["pageno"] + 1)."'>Next</a>";
}
?>
You might notice that I am not a very good coder, so if you find a less messy way to do this please let me know.
Cheers!

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.

Pagination does not work perfectly

I have the following code:
$max = 4;
$page = isset($_GET['page']) ? ($_GET['page']) : '1';
$init = $page - 1;
$init= $max * $init;
$strCount = "SELECT COUNT(*) AS 'total_mytable' FROM mytable";
$varstrCount = $crud->viewdatas($strCount);
$total = 0;
if(count($varstrCount)){
foreach ($varstrCount as $row) {
$total = $row["total_mytable"];
}
}
$result = "SELECT * FROM mytable ORDER BY id_mytable LIMIT $init,$max";
$varresult = $crud->viewdatas($result);
content of page:
<?php
if(count($varresult)){
foreach ($varresult as $res) {
?>
<h5><?php echo $res['title'] ?></h5>
<?php
}
}
?>
<?php
$max_links = 10;
$previous = $page - 1;
$next = $page + 1;
$pgs = ceil($total / $max);
if($pgs > 1 ){
if($previous > 0){
echo "<li><a href='".BASE_URL."/category/$previous' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>";
} else{
}
for($i=$page-$max_links; $i <= $pgs-1; $i++) {
if ($i <= 0){
}else{
if($i != $page{
if($i == $pgs){ //if end insert 3 dots
echo "<li><a href='".BASE_URL."/category/".($i)."'>".$i."</a></li> ...";
}else{
echo "<li><a href='".BASE_URL."/category/".($i)."'>".$i."</a></li>";
}
} else{
if($i == $pgs){ //if end insert 3 dots
echo "<li>".$i."</li> ...";
}else{
echo "<li>".$i."</li>";
}
}
}
}
if($next <= $pgs){
echo "<li><a href='".BASE_URL."/category/$next' aria-label='Next'><span aria-hidden='true'>»</span></a></li>";
}else{
}
}
?>
The result:
And I not understand the reason for the active number stay right off the paging menu
In the code I defined max-links for 10, but no show number 5 and if I define max links for 3 changes nothing , displays the same result as the image.
Thanks for any help
echo "<li>".$i."</li>";
on the above line add up a href, seems like you have css formatting for li>a because of which you are not getting the required formatting on only li. so for getting better formatting for all paging links current, prev, next. you need to add up a tags.
echo "<li><a>".$i."</a></li>"; //in your else part

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
}

Loop through a recordset (PHP + MySQL) grouping each 2 records in a list item

I need to loop through a recordset (PHP + MySQL), grouping each 2 records in a list item
My actual code (semplified) is this:
<?php
// how many total records do I have?
mysql_select_db($database_connEIB, $connEIB);
$query_rsMediaCount = "SELECT COUNT(*) AS med_count FROM media";
$rsMediaCount = mysql_query($query_rsMediaCount, $connEIB) or die(mysql_error());
$row_rsMediaCount = mysql_fetch_assoc($rsMediaCount);
$mCount = $row_rsMediaCount['med_count']; // total records
$mPages = ceil($mCount / 2); // max LIs to create
$mIndex = 0; // useful initialization for LIMIT, see below
if ($mCount > 0) { // let's show markup only if there's some record!
?>
<ul>
<?php for ($mPage = 1; $mPage <= $mPages; $mPage++) { // create the LIs ?>
<li>
<?php
$query_rsMedia = "SELECT med_id FROM media LIMIT $mIndex, 2";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
$row_rsMedia = mysql_fetch_assoc($rsMedia);
do { ?>
<div><?php echo $row_rsMedia['med_id']; ?></div>
<?php } while ($row_rsMedia = mysql_fetch_assoc($rsMedia));
$mIndex += 2; // increment the LIMIT by 2 steps ?>
</li>
<?php } ?>
</ul>
<?php } ?>
The output is sort like this:
<ul>
<li>
<div>1</div>
<div>2</div>
</li>
<li>
<div>3</div>
<div>4</div>
</li>
<li>
<div>5</div>
</li>
</ul>
Everything works, but is there a more elegant or efficient solution?
Thanks in advance
Do only one query and group the results within the loop. Use the modulo operator %:
$query_rsMedia = "SELECT med_id FROM media";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
if (mysql_num_rows($rsMedia) > 0) { // check if there is at least one result
echo '<ul>';
$index = 0;
while ($row_rsMedia = mysql_fetch_assoc($rsMedia)) {
if ($index % 2 == 0) echo '<li>'; // open <li> bevore even result
echo '<div>'.$row_rsMedia['med_id'].'</div>';
if ($index % 2 == 1) echo '</li>'; // close <li> after odd result
$index++;
}
if ($index % 2 == 1) echo '</li>'; // close <li> if odd result count
echo '</ul>';
}
(just written, not testet)
I would try to run fewer queries.
$query_rsMedia = "SELECT med_id FROM media";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
$count = 0;
echo '<ul>';
while($row = mysql_fetch_assoc($rsMedia))
{
//check divisibility to know when to show li
if ($count % 2 == 0) {
echo '<li>';
}
echo '<div>' . $row['med_id'] . '</div>';
$count++;
if ($count % 2 == 0) {
echo '</li>';
}
}
if ($count % 2 == 1) echo '</li>';
echo '</ul>';
Ask query once without the LIMIT statement. Then do something like this:
$iteration=0;
echo '<li><ul>';
while ($row_rsMedia = mysql_fetch_assoc($rsMedia)
{
echo '<div>'.$row_rsMedia['med_id'].'</div>';
$iteration++;
if ($iteration%2==0 && $iteration<$mCount)
echo '</ul><ul>'
}
echo '</ul><li>';
I would separate the HTML and PHP for ease of reading first. Also, I am not entirely convinced of the do...while loop that actually prints the result (what if the table was empty?).
Your code also contains two distinct ideas (generating the list and getting the page count), so I would break them into two separate functions. Makes code easier top read.
It may, therefore, look like this:
<ul>
<?php generateList(); ?>
</ul>
<?php
function getPageCount() {
mysql_select_db($database_connEIB, $connEIB);
$query_rsMediaCount = "SELECT COUNT(*) AS med_count FROM media";
$rsMediaCount = mysql_query($query_rsMediaCount, $connEIB) or die(mysql_error());
$row_rsMediaCount = mysql_fetch_assoc($rsMediaCount);
$mCount = $row_rsMediaCount['med_count'];
$mPages = ceil($mCount / 2);
}
function generateList()
$mIndex = 0;
$mPages = getPageCount();
if ($mCount > 0) {
for ($mPage = 1; $mPage <= $mPages; $mPage++) {
$result = "<li>" ;
$query_rsMedia = "SELECT med_id FROM media LIMIT $mIndex, 2";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
$row_rsMedia = mysql_fetch_assoc($rsMedia);
while ((row_rsMedia = mysql_fetch_assoc($rsMedia)) != null) {
$result .= "<div>".$row_rsMedia['med_id']."</div>";
}
$mIndex += 2;
$result .= "</li>
}
echo $result;
}
?>
Hope it helps.

Categories