Divide mysql query to fit divs - php

Sorry if the title is a bit confusing, I tried my best!
So basically I have 4 column divs that each contains 5 links for example. The links come from a table in my database, so new links are added and some others deleted, hence why I need to do it via database instead of writing it by hand. Now my issue is to divide the array in order to show 5 links per column (so when 5 links have been placed, div is closed and a new one is opened, unless there is no more link.
for example:
<div class="column">
Link
Link
Link
Link
Link
</div>
<div class="column">
Link
Link
Link
Link
Link
</div>
etc.
Thanks to anyone!

The PHP function array_chunk is nice to distribute an array of links into columns:
$columns = array_chunk($rows, 5);
foreach ($columns as $links)
{
echo '<div class="column">', "\n";
foreach ($links as $link)
printf("Link", $link);
echo '</div>', "\n";
}
I don't know your column names nor how you query the database, so I don't have any array indexes here written out. But I think you'll get the idea.

How about using the modulo operator
<div class="column">
for ($i = 0; $i < $nRow; $i++) {
if ($i % 5 == 0 && $i) {
echo '</div><div class="column">';
}
echo "<a href='{$links[$i]}'>Link</a>";
}
</div>

Related

How to create simple pagination in PHP page

Below is my Code.
<?php
$folder_name=$_GET['folder_name'];
$dirname = "customized_kits/images/";
$images = glob($dirname."*");
$filecount = count( $images );
$i=0;
for($i=0;$i<200;$i++) { ?>
<div class="col-md-2"> <div class="photos">
<div id="images1">
<a href=# data-lightbox="roadtrip">
<?php
if($filecount>$i) {
$filename = substr($images[$i], strrpos($images[$i], '/') + 1);
echo '<img src="'.$images[$i].'" style="width:150px;height:150px" /><br/>';
?>
<i class="fa fa-remove"></i>
<?php } else {
echo '<a ><img style="width:150px;height:150px;background-color:#eee" /></a>';
} ?>
</div>
</div>
</div>
<?php } ?>
Here I created 200 boxes with foreach loop I want to show 20 divs for single page and with help of pagination I want to show other divs.I searched in many websites I didnt get exact answer please help me to get out of this issue.
Okay so from your code you can have 200 values of $i and you want to paginate them in segments of 20. Let us start off by adding a script above your code to get the range that needs to be displayed. Page number comes as a GET parameter in number. ex example.com/feeds?number=2.
<?php
$pageno = $_GET['number']; // Page number from frontend
// Now this value will give you 1,2,3 etc
$start = $pageno*20;
// $start contains the initial offset or the value of `$i` from to start
for($i=$start;$i<$start+20;$i++) {
// Will only show 20 elements on the page
}
?>
Remember this is a very basic example. Although i would recommend using range in sql query instead so you don't have to load the complete dataset in each query.
More explanation
Suppose you have M results and you want to show N results on each page, the results on page x would start from x*N to x*(N+1) pure math here. In your code you are iterating $i over the whole loop rather just iterate over that specific range to get results. The value of x is the example is the page number that we get from number in GET verb.

PHP: two column lists lay out

I'm listing some movies in my web so the user can choose the best movie.
I’m classifying them by genre.
But the lists under each genre are too long and I want to make two columns of titles.
The number of movies in each column will depend of the genre.
So my code is like this now:
$i = 1;
echo "<ul>";
foreach($arrayMovies as $k=>$v)
{
echo "<li><input type=\"checkbox\" id=\"flat-$i\" name=\"$genre-$i\" value=\"$k\">
<label for=\"flat-$i\">$v</label></li>";
$i++;
}
echo "</ul>";
This code is showing the long list, something like this for drama:
Forest Gump
The Hours
Mullholand Drive
Titanic
.
.
Let’s say that for the drama genre I need two titles per column:
<ul>
<li> Forest Gump</li>
<li> The Hours</li>
</ul>
<ul>
<li> Mullholand Drive</li>
<li> Titanic</li>
</ul>
How can achieve this with my code??
The second column I can achieve by using css, I just need a new <ul> after two titles.
Please notice that the number two in -two titles per column- is a dynamic number*
*I’ll count how many rows per title each genre has to get a total number and then I’ll do half of it to get the number of titles per column (the number of titles in each genre is even)
Thanks very much!
Just insert those UL tags at the half of the iterations:
$arrayMovies = array( 'Forest Gump', 'The Hours', 'Mullholand Drive', 'Titanic', 'The Intouchables' );
$arrayMoviesCount = count( $arrayMovies );
echo '<ul>';
for( $i = 0; $i < $arrayMoviesCount; $i++ )
{
if( ceil( $arrayMoviesCount / 2 ) == $i )
{
echo '</ul><ul>';
}
echo sprintf( '<li>%s</li>', $arrayMovies[$i] );
}
echo '</ul>';
Output of the above code:
<ul>
<li>Forest Gump</li>
<li>The Hours</li>
<li>Mullholand Drive</li>
</ul>
<ul>
<li>Titanic</li>
<li>The Intouchables</li>
</ul>
The ceil is required for lists with an odd number of entries; using ceil will result in the first list having one entry more. If the additional (not-even) entry should be displayed in the second list, you could replace ceil by floor.
Sorry for the previous answer, I didn't understand what you wanted to exactly do.
If the problem is: "I want to categorize movies", then use an associative array instead.
Else, if you just want to display two movies in two coloumns, I would suggest you this:
$i = 1;
$flagCounter = 0;
echo "<ul>";
foreach($arrayMovies as $k=>$v)
{
if ($flagCounter != 2) {
echo "<li><input type=\"checkbox\" id=\"flat-$i\" name=\"$genre-$i\" value=\"$k\">
<label for=\"flat-$i\">$v</label></li>";
$i++;
$flagCounter++;
}
else {
echo "</ul><ul>";
echo "<li><input type=\"checkbox\" id=\"flat-$i\" name=\"$genre-$i\" value=\"$k\">
<label for=\"flat-$i\">$v</label></li>";
$i++;
$flagCounter = 1;
}
}
echo "</ul>";
To be honest at all, I don't really trust this solution, this is just a workaround for your case. If you're interested in a better one, try using an associative array with a structure like such:
$yourArray = array ( "Category" => array ("movie1","movie2") [and so on...] );
In this way, you will be able to display everything more clearly, being able to access to both movies and categories!
Also, why did you choose to use a list instead of a table for displaying these?
And.. Where does the variable $genre come from? Is this all your code or what? If not, can you please provide us the structure of your array?

Attempting to loop through 2 arrays simultaneously [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Multiple index variables in PHP foreach loop
I am trying to create a before and after image display using mysqli, php and html.
I am pulling the records from the db with mysqli and php, and am trying to view the results in an Unordered List using a foreach loop.
I have my 2 arrays which are created above in a while loop of a mysqli query. The array will only contain 5 results (for pagination, may change later).
$before_array[] = '
<div class="highslide-gallery">
<li>
<a href="'.$beforeurl.'" class="highslide" onclick="return hs.expand(this)">
<img src="'.$beforeurl.'" width="100px" height="125px" alt="Highslide JS">
</a>
</li>';
$after_array[] = '
<li><a href="'.$afterurl.'" class="highslide" onclick="return hs.expand(this)">
<img src="'.$afterurl.'" width="100px" height="125px" alt="Highslide JS">
</a>
</li>';
and in the view of the page I have the following code to display the before and after pictures.
<div id="hoverwrap">
<ul class="hoverbox">;
<?php
foreach ($before_array as $value) {
echo $value;
}
foreach ($after_array as $value) {
echo $value;
}
?>
</ul>
</div><!-- end of hoverwrap div-->
With the current code it is displaying the pictures :
before - before - before - before - before - after - after - after - after - after.
Where I would like it to diplay:
before - after - before - after etc etc.
I was thinking a while loop but no matter which way I try and implement it, it results in a similiar display.
Any help or pointers in the right direction will be greatly appreciated.
Thanks.
A for loop will do the trick here:
$x = count($before_array);
for($i = 0; $i < $x; $i++) {
print $before_array[$i];
print $after_array[$i];
}
Why can't you print it in the mysql loop itself?

how can put value in two columns?

how can a list of values that select of database, put in two columns together by PHP ?
EXAMPLE:
values select of database:
Internet
Game Notes
Internet
Pool
Coffee
Game Notes
i want like this:
Row-first order
<table>
<?php
$left = true;
foreach ($values as $value){
if ($left)
echo "<tr>";
echo "<td>$value</td>";
if (!$left)
echo "</tr>";
$left = !$left;
}
?>
</table>
With column-first order (as in your sample) you'll have to involve CSS and it's much complex. Something like
<div class='inline_div'>
<?php
$middle = count($values)/2+1;
$count = 0;
foreach ($values as $value){
if ($count==$middle)
echo "</div><div class='inline_div'>";
echo "$value<br/>";
++$count;
}
?>
</div>
inline_div is something like .inline_div {display:inline; float:left}. But that will definitely not work as expected, I'm no CSS master. IE does not support display:inline for sure.
If you want it exactly like you want in your example then you are going to have to read the whole table into memory, calculate the mid-point element and then build your table from that using a base point, an offset and a check to ensure that you've not repeated anything which involves a whole load of calculation.
A way around this would be to build two separate tables (each containing a single column) and then enclose them in a single table with two columns:
<?php
$list=array('a','b','c','d','e','f');
$midpoint=floor(count($list)/2);
$tableHeader='<table width="100%">';
$tableFooter='</table>';
$leftTable=$tableHeader;
$rightTable=$tableHeader;
for ($c=0; $c<$midpoint; $c++)
{
$leftTable.='<tr><td width="100%">'.$list[$c].'</td></tr>';
}
$leftTable.=$tableFooter;
for ($c=$midpoint; $c<count($list); $c++)
{
$rightTable.='<tr><td width="100%">'.$list[$c].'</td></tr>';
}
$rightTable.=$tableFooter;
$mainTable='<table><tr><td width="50%">'.$leftTable.'</td><td width="50%">'.$rightTable.'</td></tr></table>';
echo $mainTable;
?>
Or something along those lines. I haven't tested this code but it would be pretty close (may have to adjust the values in the "for" sections
The simple solution would be to use two divs. As a previous poster commented, you first need to count the elements. Suppose the items you want to display are in an array $items You can use this kind of code
<?php
$divItemCount = (count($items)%2) ? count($items)/2 + 1 : count($items)/2;
?>
<div id="leftdiv" style="width: 30%;">
<ul>
<?php
for($i=0; $i<$divItemCount; $i++) {
echo '<li>'. $items[$i] .'</li>';
}?>
</ul></div><div id="rightdiv" style="width: 30%; float:left"><ul>
<?php
for($j=$i; $j<count($items); $j++) {
echo '<li>'. $items[$j] .'</li>';
}?>
</ul></div>
I have not tested the code so there may be errors. You can use the border property in the divs to create a custom separator between the two lists.

Multi column dynamic PHP list

So what I'm trying to do is select all the distinct months from my database and then print them in a list. That, I can accomplish. The problem lies in the fact that I need my list to be two column. The way that I achieve this with CSS is by using 2 different div's "left" and "right" which are floated next to each other. This poses a problem with PHP because it needs to echo a div close and a new div open after it echoes the sixth month. Then it needs to start again from where it left off and finish. I can't just list all of the months in the HTML, either because I don't want it to list a month if I don't have any records in the DB for that month, yet. Any ideas? I hope I was clear enough!
Thanks!
-williamg
Something like this should work (the basic idea being to just keep a count of the months an increment it as you loop through them):
<div class="left">
<?php
$x = 1;
foreach($months as $month) {
# switch to the right div on the 7th month
if ($x == 7) {
echo '</div><div class="right">';
}
echo "<div class=\"row\">{$month}</div>";
# increment x for each row
$x++;
}
</div>
<?php
$numberOfMonths = count($months);
$halfwayPoint = ceil($numberOfMonths / 2);
echo "<div class=\"left\">";
for($i=0; $i<$halfwayPoint; $i++){
echo $months[$i] . "<br />";
}
echo "</div><div class=\"right\">";
for($i=$halfwayPoint; $i<$numberOfMonths; $i++){
echo $months[$i] . "<br />";
}
echo "</div>";
?>
Rant: on
When displaying tabular data, use table instead of floating div. It will make sense when viewing the page with css disabled. If you use floated div, then you data will displayed all way down. Not all table usage is bad. People often hate table so much, so using floated div. Table only bad when used for page layout.
Rant: off
When I need to have certain content displayed with some open, close, and in-between extra character, I will make use of implode. This is the example:
$data = array('column 1', 'column 2');
$output = '<div>'.implode('</div><div>', $data).'</div>';
//result: <div>column 1</div><div>column 2</div>
You can extends this to almost anything. Array and implode is the power that php have for many years. You will never needed any if to check if it last element, then insert the closing character, or check if it first element, then insert opening character, or print the additional character between elements.
Hope this help.
Update:
My bad for misread the main problems asked. Sorry for the rant ;)
Here is my code to make a data displayed in 2 column:
//for example, I use array. This should be a result from database
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
//should be 12 month, but this case there are only 9 of it
for ( $i = 0; $i <= 5; $i++)
{
//here I do a half loop, since there a fixed number of data and the item for first column
$output = '<div class="left">'.$data[$i].'</div>';
if ( isset($data[$i+6] )
{
$output = '<div class="right">'.$data[$i+6].'</div>';
}
echo $output."\n";
}
//the result should be
//<div class="left">1</div><div class="right">7</div>
//<div class="left">2</div><div class="right">8</div>
//<div class="left">3</div><div class="right">9</div>
//<div class="left">4</div>
//<div class="left">5</div>
//<div class="left">6</div>
Other solution is using CSS to format the output, so you just put the div top to down, then the css make the parent container only fit the 6 item vertically, and put the rest to the right of existing content. I don't know much about it, since it usually provided by fellow css designer or my client.
Example assumes you have an array of objects.
<div style="width:150px; float:left;">
<ul>
<?php
$c = count($categories);
$s = ($c / 3); // change 3 to the number of columns you want to have.
$i=1;
foreach($categories as $category)
{
echo '<li>' . $category->CategoryLabel . '</a></li>';
if($i != 0 && $i % $s == 0)
{
?>
</ul>
</div>
<div style="width:150px; float:left;">
<ul>
<?php
}
$i++;
}
?>
</ul>
</div>

Categories