PHP: split a mySQLi array in two divs? - php

I'm currently working on a page that calls a mySQL database to populate a list of members. However, I need that list to be split into two equal parts, so that half can float to the left and half to the right. However, I have beat this horse to death and still cannot figure out how to split the array.
Here's what I have currently:
<div class="holder">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
if ( $rowcount > 0 ) { ?>
<div class="members-left">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
//SOME CONTENT HERE
</li>
<?php } ?>
</ul>
</div>
<?php } ?>
</div>
However, I want the output to look something like this (let's say my table has 10 members):
<div class="holder">
<!--output first half of members from table: -->
<div class="members-left">
<ul class="members">
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
</ul>
</div>
<!--output second half of members from table: -->
<div class="members-right">
<ul class="members">
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
</ul>
</div>
</div>
I've tried setting counters and using things like if($i <= $rowcount/2), but to no avail. Any help would be greatly appreciated—I'm very new to mySQL and have limited knowledge of PHP, so this one has me stumped.

add a control variable like "$i". add +1 to $i every loop. and check if $i reached half of number of rows. if reached close ul and div and open new div and ul and set $i to 0
<div class="holder">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
$i=0;
if ( $rowcount > 0 ) { ?>
<div class="members-right">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
//SOME CONTENT HERE
</li>
<?php
$i++;
if($i>=($rowcount/2)){
echo '</ul></div>
<div class="members-right">
<ul class="members">';
$i=0;
}
} ?>
</ul>
</div>
<?php } ?>
</div>

You could use a for loop for the first half and just finish the second half with a while loop that goes until there are no more results.
First half:
for($i = 0; $i <= $rowcount/2 && $row = $members->fetch_assoc(); $i++)
Second half
while ($row = $members->fetch_assoc())
Example with HTML
<div class="members-left">
<ul class="members">
<?php for($i = 0; $i <= $rowcount/2 && $row = $members->fetch_assoc(); $i++) { ?>
<li class="member">
// do something with $row
</li>
<?php } ?>
</ul>
</div>
<div class="members-right">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
// do something with $row
</li>
<?php } ?>
</ul>
</div>

I would recommend you to make 2 arrays of your members and then print them out. The advantage is you will have more control of the members and your code will be more readable for later use;
<?php
$i =0;
while ($row = $members->fetch_assoc()) {
if($i % 2 == 0)
{
$right_members[] = $row;
}
else
{
$left_members[] = $row;
$i++;
}
echo '
<div class="members-right">
<ul class="members">';
foreach($right members as $r_member){
echo '<li class="member">...</li>';
}
echo '
</ul>
</div>';
//SAME WITH LEFT MEMBERS
?>

Having a counter was an idea, I will not debate on having model logic in view ;)
well, a solution would be :
<div class="holder">
<div class="members-column">
<ul class="members">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
$i = 0;
while ($row = $members->fetch_assoc()) {
?>
<li class="member">
//SOME CONTENT HERE
</li>
<?
// Check if current row is the 'middle count', creating a new column
if ($i === ceil($rowcount / 2)) : ?>
</ul>
</div>
<div class="members-column">
<ul class="members">
<?php endif; ?>
<?php
$i++;
}
?>
</ul>
</div>
</div>

Related

creating class active dynamically in php

I am creating a menu dynamically based on the categories registered on the dataBase, What I need is:
When someone click in the link, this option should have the css class 'active', showing in with page the user is and even the pages are created dynamically.
I have no idea how to do this because I am php student and I couldn't find this information in google for "Dynamically menus" Thank you very much.
<nav class="menu">
<ul class="list">
<li class="line"><a id="item" href="index.php">Home</a></li>
<?php
$categories = $db->select("select * from tbl_category");
if($categories){
while ($result = $categories->fetch_assoc()){
echo <<<HTML
<li id="line" ><a class="item" href="categories.php?category=$result[id]">$result[name]</a></li>
HTML;
}
}
?>
</ul>
<nav>
First of all, you're looping through that while loop and adding the id of "line" to each and every <li> element. I suggest you create unique id's for each list item. I don't necessary advocate using the code the way you have it, just as an example, here's your code edited to do just that:
if($categories){
$i = 1;
while ($result = $categories->fetch_assoc()){
$i++;
echo <<<HTML
<li id="line$i" ><a class="item" href="categories.php?category=$result[id]">$result[name]</a></li>
HTML;
}
}
Then when someone clicks on your link, just use jQuery with something like this:
$(".item").click(function() {
$(this).parent('li').addClass('active');
});
Try something like that:
<nav class="menu">
<ul class="list">
<li class="line"><a id="item" href="index.php">Home</a></li>
<?php
$current_page = isset($_GET['category']) ? $_GET['category']: -1;
$categories = $db->select("select * from tbl_category");
if($categories){
while ($result = $categories->fetch_assoc()){
echo '<li id="line">';
if($result['category'] === $current_page) {
// If we're currently in the active page then add the active class to the <a>
echo '<a class="item active" href="categories.php?category='. $result[id] .'">';
} else {
echo '<a class="item" href="categories.php?category='. $result[id] .'">';
}
echo $result['name'];
echo '</a>';
echo '</li>';
}
}
?>
</ul>
<nav>
Thank you all for help, based on your code, I solved doing this:
menu.php:
<nav class="menu" id="menu">
<ul id="list" class="list">
<li id="line" class="<?php if($presentPage == '0')echo 'active';?>"><a id="item" class="item" href="index.php">Home</a></li>
<?php
function checked($pp, $id){
if($pp == $id){
$status = 'active';
return $status;
}
}
$query = "select * from tbl_category";
$category = $db->select($query);
if($category){
while ($result = $category->fetch_assoc()){
echo "
<li id='line' class='".checked($presentPage, $result['id'])."'><a id='item' class='item' href='categories.php?category=".$result['id']."'>".$result['name']."</a></li>
";//end echo
}//end while
}//end if
?>
</ul>
</nav>
In my index.php:
<?php $presentPage = 0;?>
<?php require_once 'header.php';?>
<?php require_once 'menu.php';?>
and in my categories.php:
<?php
if (!isset($_GET['category']) || $_GET['category'] == NULL) {
$presentPage = 0;
}else{
$presentPage = intval($_GET['category']);//just to make sure that the variable is a number
}
?>
<?php require_once 'header.php';?>
<?php require_once 'menu.php';?>
///...my code...
and in my CSS of course:
.active{
background: linear-gradient(#821e82, #be5abe);
}
Thats is working perfectly for me, Thank for all help.

Limiting number of items to display per page

I have files like (for an instance ) being shown as shown in
http://lawcommission.gov.np/site/NepalLawCommissionFinal/NepalLawCommissionFinal/document.php?cat=112&sub_cat=10008
The document.php has following html to display the files:
<section class="three-fourth">
<div class="sort-by">
<h3>Sort by</h3>
<ul class="sort">
<li>Date ascendingdescending</li>
<li>Name ascendingdescending</li>
<li>Category ascendingdescending</li>
</ul>
<ul class="view-type">
<li class="grid-view">grid view</li>
<li class="list-view">list view</li>
</ul>
</div>
<div class="deals clearfix">
<!--deal-->
<?php
$id = $_GET['cat'];
$base_obj = new Base();
$lst = $base_obj->list_doc($id);
$lst->execute();
foreach ($lst as $rec)
{
$sub_head = $rec['Head_Id'];
$get_sub = $base_obj->list_by_id('Head_Id', $sub_head, 'tbl_heading');
$get_sub->execute();
foreach ($get_sub as $h)
{
$heading = $h['Head_Name'];
}
?>
<article class="one-fourth">
<figure><span style="float:left"><img src="images/uploads/london1.jpg" alt="" style="width:100px" /></span><span style="float:left"></span></figure>
<div class="details">
<h1><?=$rec['Doc_Name'];?></h1>
<span class="address"><?=$heading;?></span>
<span class="price">Added On <em><?=substr($rec['Uploaded_Date_Time'],0,10);?></em> </span>
Download
</div>
</article>
<!--//deal-->
<?php
} ?>
<!--bottom navigation-->
<div class="bottom-nav">
<!--back up button-->
Back up
<!--//back up button-->
<!--pager-->
<div class="pager">
<span>First page</span>
<span><</span>
<span class="current">1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
<span>7</span>
<span>8</span>
<span>></span>
<span>Last page</span>
</div>
<!--//pager-->
</div>
<!--//bottom navigation-->
</div>
</section>
<!--//three-fourth content-->
</div>
<!--//main content-->
</div>
<div class="wrap clearfix">
<!--info boxes--><!--//info boxes-->
</div>
Can you guys please suggest a way to show only limited no. of pdf files in one page?
here is how you need to change your function:
public function list_doc($cat, $page=0) {
$itemsPerPage = 20;
$cat = intval($cat, 10);
$start = intval($page, 10) * $itemsPerPage;
if ($start < 0) $start = 0;
$qry = $this->dbobj->db1->prepare("SELECT SQL_CALC_FOUND_ROWS *
FROM tbl_documents, tbl_cat_head_doc
WHERE tbl_cat_head_doc.Cat_Id = " . $cat ." AND
tbl_cat_head_doc.Doc_Id = tbl_documents.Doc_Id AND
tbl_documents.Status = 'a'
limit " . $start . "," . $itemsPerPage);
return $qry;
}
and in main page call function like this:
$lst = $base_obj->list_doc($id, $_GET['page']);
to prevent next question: read about SQL_CALC_FOUND_ROWS and FOUND_ROWS()

Adding a class name to every fouth item in a forloop

I'm used to doing this with Django and it's fairly simple, so trying to workout how it's done in PHP. What I'd like to do is within a PHP for foreach loop I would like to add the class name of 'last' to every fourth item in the list.
PHP code:
<?php
$products = array();
$product_counter = 0;
foreach ($_productCollection as $_product)
{
?>
So this is my current HTML output:
<li>
<div class="contentWrap"> content here </div>
</li>
<li>
<div class="contentWrap"> content here </div>
</li>
<li>
<div class="contentWrap"> content here </div>
</li>
<li>
<div class="contentWrap"> content here </div>
</li>
However, what I would like to acheive is:
<li>
<div class="contentWrap"> content here </div>
</li>
<li>
<div class="contentWrap"> content here </div>
</li>
<li>
<div class="contentWrap"> content here </div>
</li>
<li>
<div class="contentWrap last"> content here </div>
</li>
I was using the nth child attribute in CSS3 but it needs to be supported in IE8!
Anyway, PHP isn't my strong point and can't make use of the examples i've found online so any help would be much appreciated.
Thanks
Use something like this:
$counter = 0;
foreach ($_productCollection as $_product) {
//whatever
if ($counter % 4 == 3) {
//do stuff for every 4th element
}
$counter++;
}
Simple right?
for($i = 0; $i < $countOfArray; $i++) {
if($i % 4 == 3) {
// add last class ....
}
}

Place DIV's in a containing DIV based on a numeric value

Ive got the follow PHP:
<div class="slide-background">
<div class="slide">
<?php foreach (array_chunk($items->submenu, $linkCount) as $items): ?>
<?php if (12 / $cols == 1):?>
<div class="col-md-12">
<?php else: ?>
<div class="col-md-<?php echo 12 / $cols; ?>">
<?php endif; ?>
<ul>
<?php foreach($items as $submenu): ?>
<?php echo $submenu; ?>
<?php endforeach; ?>
</ul>
</div>
<?php endforeach; ?>
</div>
<ul class="pager">
<li>prev</li>
<li>next</li>
</ul>
</div>
</div>
basically it calculates how many links to display and how many columns, but i now need to place the links in <div class="slide"></div>, but based on the columns.. so basically i need to say if $cols = 2 place two div's in a div and close.. so its basically how many every $cols it should place so many div's in that div..
Its Confusing for me to even explain.. I think Ive explained it rather well above.. If not place say so and ill try again..
Any Help Greatly Appreciated..
UPDATE:
thanks to Hans ive now have the following:
<?php $linksPerColumn = ceil($linkCount / $cols); $linkCounter = 0;?>
<div class="slide-background">
<div class="slide">
<div class="col-md-<?php echo 12 / $cols ?>">
<ul>
<?php foreach ($items->submenu as $link): ?>
<?php $linkCounter++;?>
<?php if($linkCounter % $linksPerColumn == 0):?>
</ul>
</div>
<div class="col-md-<?php echo 12 / $cols ?>">
<ul>
<?php endif; ?>
<?php echo $link; ?>
<?php endforeach; ?>
</ul>
</div>
</div>
<ul class="pager">
<li>prev</li>
<li>next</li>
</ul>
</div>
</div>
only problem is when there's only one column and i need 2 links and then for it to close the div and the ul and start new ones.. right now it does that except for everyone and not for every two links...
You could use modulus for this one. You should calculate how many items you need per column. And then create a close and open div for example:
<?
$linksPerColumn = 4;
if ($linkCount > 4){
$linksPerColumn = ceil ($linkCount / $amountOfColums);
}
$linkCounter = 0;
?>
<div class="slide-background">
<div class="slide">
<?
foreach ($links as $link)
{
$linkCounter++;
?>
// Do your HTML Here.
<?
if($linkCounter % $linksPerColumn = 0)
{
?>
</div>
<div class="slide">
<?
}
?>
</div>
</div>
// Rest of the HTML here.
I think this should do the trick for you.

how to format the display of results after a sql query

i have been trying to format my results which is being sorted by the first letter of the surname but having problems
i need it to echo in the following format
<section>
<div id="slider">
<div class="slider-content">
<ul>
<li id="LETTER"><a name="LETTER" class="title">LETTER</a><ul>
<li>SURNAME</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</section>
i am have tried to split it so (see code bellow) but it not rendering correctly
<html>
<head>
<title>MySQLi Read Records</title>
</head>
<body><section>
<div id="slider">
<div class="slider-content">
<ul>
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = " SELECT name,
surname,
mobile,
UPPER (LEFT(surname, 1)) AS letter
FROM contacts
ORDER BY surname";
//execute the query
$result = $mysqli->query( $query );
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
if( $num_results > 0){ //it means there's already a database record
//creating our table heading
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
if (!isset($lastLetter) || $lastLetter != $row['letter'])
{
echo '<li id="', $row['letter'], '"><a name="', $row['letter'],'" class="title">', $row['letter'],'</a><ul>';
$lastLetter = $row['letter'];
echo "bottom";
}
echo "<li><a href='#'>{$surname} - {$name}</a></li>";
}
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?> </ul>
</li>
</ul>
</div>
</div>
</section>
</body>
</html>
i need to find where and how to echo these sections so it would be like this
:- UPDATE -:
with the reply i got itested it and it goes something like this
<body>
<section>
<div id="slider">
<div class="slider-content">
<ul>
<li id="E"><a name="E" class="title">E</a>
<ul>
bottom
<li><a href='#'>egg - smash</a></li>
<li id="S"><a name="S" class="title">S</a>
<ul>
bottom
<li><a href='#'>surname</a></li>
<li><a href='#'>surname</a></li>
<li><a href='#'>surname</a></li>
<li id="Z">
<a name="Z" class="title">Z</a>
<ul>
bottom
<li><a href='#'>zoo</a></li>
<!-- </ul> BAD UL ?-->
</li>
</ul>
</div>
</div>
</section>
</body>
</html>
when it should be
<section>
<div id="slider">
<div class="slider-content">
<ul>
<li id="s"><a name="s" class="title">s</a><ul>
<li>surname</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</section>
ALWAYS indent your code, AlWAYS run tests on variables, do not take steps skipping simple testing before like looping
<body>
<section>
<div id="slider">
<div class="slider-content">
<ul>
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = " SELECT name,
surname,
mobile,
UPPER (LEFT(surname, 1)) AS letter
FROM contacts
ORDER BY letter ASC";
//execute the query
$result = $mysqli->query( $query );
//TEST 1st print_r($result); if not working there is an error on your sql
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
if( $num_results > 0){ //it means there's already a database records
//creating our table heading
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
if (!isset($lastLetter) || $lastLetter != $row['letter'])
{
echo '<li id="', $row['letter'], '"><a name="', $row['letter'],'" class="title">', $row['letter'],'</a><ul>';
$lastLetter = $row['letter'];
echo "bottom";
}
echo "<li><a href='#'>{$surname} - {$name}</a></li>";
}
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
<!-- </ul> BAD UL ?-->
</li>
</ul>
</div>
</div>
</section>
</body>

Categories