Adding 4 item per row in PHP - php

I have some HTML in a variable that I'd like to loop 4 time per row. I am making a couple of queries first. In one I get the number of rows and store it in a variable. The second, I am looking to fetch the associated data that I will need to display.
$results = $dbCon->query("SELECT * FROM table WHERE status = '1' ORDER BY id DESC LIMIT $start, $limit");
$total = mysqli_num_rows($results);
$res = $dbCon->query($results);
$data = $res->fetch_assoc();
$link = $data['link'];
$title = $data['title'];
$image = $data['image'];
$imgAlt = $data['imgAlt'];
Third, I store what I want to display in a variable. The HTML I plan on displaying looks something like this
$html = printf("<div style=\"text-align:center; max-width:270px; white-space:normal; word-wrap:break-word; border-left:1em solid transparent; border-right:1em solid transparent; text-overflow: ellipsis; float:left;\">
<a href=\"%s\">
<img style=\"width:270px; height:232px; margin-bottom:40px; border-radius:45px; -moz-border-radius:45px; -webkit-border-radius:45px; box-shadow:0px 0px 3px #fff; -moz-box-shadow:0px 0px 3px #fff; -webkit-box-shadow:0px 0px 3px #fff;\" src=\"images/recentshoots/%s\" alt=\"%s\" />
<p>%s</p> <br /></a>
</div>", $link, $image, $imgAlt, $title);
Next, I would like to loop the 20 items per page in 4 items per row. This is where I am having some trouble. My issue is that the number of characters in the $title are always different so the layout breaks apart. At first a tried a simple way using css and php to do a str_pad() but it doesn't seem to work right with empty spaces. I always get some containers that are taller than others which distorts my row. So I did some research in this platform to model after someone else example.
I m having some trouble with what I found because the examples I've seen have information missing that I need to understand how to modify my own. I have seen it done with foreach and while loops. Can someone help me find a way to understand this better?
How can I loop the data retrieved and make sure that only 4 per row exist in a page of 20 items? Thank you so much for your help. I started with something like this
$startingPoint = 1;
echo "<div class=\"row\">";
foreach($startingPoint < 4){ //this foreach is not even starting the right way, how can I fix this?
echo $html;
}
Can I use a foreach? or a while loop? or do-while?
which one is the best solution and the fastest or most efficient way to go? The shorter the code the better.

Foreach loops are used for array datatypes whilst a while loop can be used for booleans and more.
What you're looking for is a for loop, this allows your to set a counter and each time the loop is ran it adds to a counter. Once the expression is met, it ends the loop.
for($i = 1; $i == 4; $i++)
{
echo 'Loop ' . $i . ': This will loop 4 times';
}
However, you could fix your foreach by using this snippet:
$startingPoint = [1,2,3,4];
foreach($startingPoint as $start)
{
echo $html;
}
Since there are 4 items inside the array, the loop will continue 4 times.
Your SQL is returning more than one row of data thus creating $data to become multidimensional, your loop therefore may not work how its written, you could try this:
for($i = 1; $i >= $limit; $i++)
{
print_f(<!-- html here -->, $data[$i]['column']);
}

You can try this code. Full pagination and view:
Example: index.php
<?php
//get page id for pagination and limit query
$limit = 4;
if(isset($_GET["page"]))
$page = intval($_GET["page"]);
else
$page = 1;
$total = $limit * $page;
$start = $total - $limit;
//GEt data from database. I have used mysqli for testing purpose.
$conn=mysqli_connect("localhost","root","","dbname");
$result = mysqli_query($conn, "SELECT * FROM table WHERE status = '1' ORDER BY id DESC LIMIT $start, $limit");
$total = mysqli_num_rows($result);
?>
<!--Your html code what you want-->
<table>
<tr>
<th>Title</th>
<th>Image</th>
<th>Link</th>
</tr>
<!--loop inside html-->
<?php while($data = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $data['title']; ?></td>
<td><img src="<?php echo $data['image']; ?>" alt="<?php echo $data['imgAlt']; ?>"> </td>
<td>Link</td>
</tr>
<?php } ?>
</table>
<?php
/**======== Pagination Url generate=============*/
$totalPages = ceil($total/$limit);
if($page <=1 ){
" <span style='font-weight: bold;'> < Prev </span> ";
}else{
$j = $page - 1;
echo " <a href='index.php?page=$j'>Prev</a> ";
}
for($i=1; $i <= $totalPages; $i++){
if($i<>$page){
echo " <a href='index.php?page=$i'>$i</a> ";
}else{
echo " <span style='font-weight: bold;'>$i</span> ";
}
}
if($page == $totalPages ){
echo " <span style='font-weight: bold;'>Next ></span> ";
}else{
$j = $page + 1;
echo " <a href='index.php?page=$j'>Next</a></span> ";
}
?>

Related

create table with loop in Php

What I want is show the total clicks per Category id of the items only for 20 items order by the highest total clicks per day.
Now I am using hard code and the result have to looks like this
So, if the item id and total clicks already fill up the
20columns (for item id and total clicks) + 2 for the tittle so means
22columns
It has to move to next row.
Because I am referring to my db, so I am using loop to create the table, and when I doing that way, I am getting this result....
The result will keep showing until the end in the left side. Thats very hard to read for report purposes. I wanted the result looks like the first figure that I've uploaded.
Here is what I am doing now:
include "Con.php";
//get the value from Get Method
$CatidValue = $_GET['CatIds'];
//(The date format would looks like yyyy-mm-dd)
$DateFrom = $_GET['DateFrom'];
$DateTo = $_GET['DateTo'];
//select the CatID
$SqlGet= "Select CatId from try where CatId = $CatidValue";
$_SqlGet = mysqli_query($connection,$SqlGet);
$TakeResultGet = mysqli_fetch_array($_SqlGet);
$CatIdTittle = $TakeResultGet ['CatId'];
echo"
For Category Id : $CatIdTittle
<br>
";
//For Loop purpose and break the value
$explodeValueFrom = explode("-",$DateFrom);
$explodeValueTo = explode("-",$DateTo);
$DateValueFrom = $explodeValueFrom[0].$explodeValueFrom[1].$explodeValueFrom[2];
$DateValueTo = $explodeValueTo[0].$explodeValueTo[1].$explodeValueTo[2];
//Loop through the date
for($Loop=$DateValueFrom; $Loop <= $DateValueTo; $Loop++){
$YearLoop= substr($Loop, 0,4);
$MonthLoop =substr($Loop, 4,2);
$DayLoop = substr($Loop, 6,2);
$DateTittleValue = $YearLoop."-".$MonthLoop."-".$DayLoop;
$trValue = "<th class='tg-amwm' colspan='2'>$DateTittleValue</th>";
echo"
<table class='tg'>
<tr>
$trValue
</tr>
";
echo"
<table class='tg'>
<tr>
<td class='tg-yw4l'>Items Id</td>
<td class='tg-yw4l'>Total Clicks</td>
</tr>
";
//to get the item id and total clicks
$SqlSelect = "select `Item Id`,`Total Clicks`,Day from try where CatId = $CatidValue and Day = '$DateTittleValue' ORDER BY `try`.`Total Clicks` DESC limit 20";
$_SqlSelect = mysqli_query($connection,$SqlSelect);
foreach ($_SqlSelect as $ResultSelect) {
$Day = $ResultSelect['Day'];
$ItemId = $ResultSelect['Item Id'];
$TotalClicks = $ResultSelect['Total Clicks'];
echo"
<tr>
<td class='tg-yw4l'>$ItemId</td>
<td class='tg-yw4l'>$TotalClicks</td>
</tr>
";
}
}
?>
you need to add td dynamically within a table for each day report ( data should be grouped by date).
You just need to float each table with the float:left css property and some percentage based on the number of tables you want on the same row. In this case, 33% will do. Take a look at this codepen: http://codepen.io/anon/pen/EgXqPk
The magic happens on:
.tg {
width: 33%;
float:left;
}
you can try i hope this perfect for you to draw a table using PHP Loop.
<?php
echo "<table border =\"1\" style='border-collapse: collapse'>";
for ($row=1; $row <= 10; $row++) {
echo "<tr> \n";
for ($col=1; $col <= 10; $col++) {
$p = $col * $row;
echo "<td>$p</td> \n";
}
echo "</tr>";
}
echo "</table>";
?>

Dynamic drop down menus using CSS and PHP/MySQL

I want to create a dynamic drop down menu using PHP and MySQL. Menus is OK but not the way I wanted.
I want the menu like this as below (sorted vertically and limiting number of items vertically and horizontally)
I tried achieving this as per below code:
<?php foreach ($result as $riw) { ?>
<div class="four columns">
<li><a href="<?php echo $riw['fmprmlink']; ?>"><?php echo
$riw['remedy_name']; ?></a> </li>
</div>
<?php } ?>
By above approach i am getting this as a result which is not rquired
and without using <div class="four columns"> the result is as below which is again not required
I want items to be arranged and shown alphabetically vertically.
A simple possibility of sorting first, then second, then etc. column.
Can something be improved.
Shows one of many possibilities.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>4 columns</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<?php
function setline($conte,$i,$count,$ILines){
$act1 = $i;
$act2 = 1*$ILines + $i;
$act3 = 2*$ILines + $i;
$act4 = 3*$ILines + $i;
echo "<li>".$conte[$act1]."</li>\n"; // 0
if ($act2 < $count){ echo "<li>".$conte[$act2]."</li>\n";}
if ($act3 < $count){ echo "<li>".$conte[$act3]."</li>\n";}
if ($act4 < $count){ echo "<li>".$conte[$act4]."</li>\n";}
}
//-----------main---------------
echo "<ul id=\"quad\">";
$anArry = array("CSS","XHTML","Semantics","Accessibility","Usability","Web Standards","PHP","Typography","Grids","CSS3","HTML5");
sort($anArry);
$count = count($anArry);
$Idiv = (int)($count/4);
if ($count - ($Idiv * 4)>0) {$ILines = $Idiv+1;} else {$ILines = $Idiv;}
for ($i = 0; $i < $ILines; $i++) {
setline($anArry,$i,$count,$ILines);
}
echo "<ul/>";
?>
</body>
</html>
Next is the normal standard look of a 4 column list.
To get it we changed only the for loop.
Sorted from left to right ( not what OP wants)
for ($i = 0; $i < $count; $i++) {
echo "<li>".$anArry[$i]."</li>\n";
}
Now that we know the matrix ...
1| 0-2 3-5 6-8 9-11
col| 1 2 3 4
---|---------------
r 1| 0 3 6 9
o 2| 1 4 7 10
w 3| 2 5 8 11
... we can write a simpler function.
function sortfor4c($cont,$i,$ILines,&$ICol,&$IRow){
echo "<li>".$cont[$ICol * $ILines - $ILines + $IRow -1]."</li>\n";
$ICol++;
if ($ICol > 4) {
$ICol = 1;
$IRow++;
}
}
....
$ICol = 1;
$IRow = 1;
for ($i = 0; $i < $count; $i++) {
sortfor4c($anArry,$i,$ILines,$ICol,$IRow);
}
style.css
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6{
margin:0;
padding:0;
}
ol,ul{
list-style:none;
}
body{
font-family:Georgia, "Times New Roman", Times, serif;
color:#333;
}
ul{
width:760px;
margin-bottom:20px;
overflow:hidden;
border-top:1px solid #ccc;
}
li{
line-height:1.5em;
border-bottom:1px solid #ccc;
float:left;
display:inline;
}
#quad li { width:25%; }
Presumably, you would want to use some sort of for loop to order the data appropriately. You could do this with PHP or you could do it with JavaScript.
Either way, you will need to process the entries returned by the server so as to limit the number of rows added to each column. The way you'll process the data depends on how it is returned by the server. If the server sends JSON data representing the data cells in question (and you're using AJAX), you'll likely need to take a javascript approach. If you plan to load all menu field data upon the initial page load, you can probably use PHP to create the menu entries.
This is an example of using a for loop to create a table using PHP. You should be able to do the same thing with either list items and/or divs. If this answer is confusing, there are numerous other examples on both SO and the internet at large.
<?php
echo "<table border='1'><br />";
for ($row = 0; $row < 5; $row ++) {
echo "<tr>";
for ($col = 1; $col <= 4; $col ++) {
echo "<td>", [YOUR MENU ENTRY GOES HERE], "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
The following code uses 2 loops to create a 4 column table from an assoc array. $z is calculated to sort rows in each column in ascending order.
$count = count($result);
$rows= floor($count/5);
for ($x = 0; $x <= $rows; $x++) {
for ($y = 0; $y <= 4; $y++) {
$z=($rows*$y)+$x+$y;
if($z<$count){
$html .="<td>".$result[$z]['fmprmlink']."</td>\n";
}else{
$html .="<td></td>\n";
}
}
$html .="</tr>\n";
}
$html .="</table>";
echo $html;

php give class to 3 div's then skip 3

I have a table with a row of 3 div's then another row or 3 div's then another and then another.
But what I'm trying to achieve is to highlight every other row. And each row contains 3 div's.
So the first row will be .mydiv .even and then the .even's will be grey. Then the next row will be .mydiv .odd and then the .odd's will be white.
I am using this code from css-tricks.com ($xyz++%2) to make every other div a different class.
All help is apreciated.
This is my code
$get_new_games = mysql_query("SELECT game_title,game_description,id from games ORDER BY added_date LIMIT 10");
while ($row = mysql_fetch_array($get_new_games)) {
$new_game_title = $row['game_title'];
$new_game_description = $row['game_description'];
$new_game_id = $row['id'];
$new_games_display .= '<div class = "game_module class-'.($xyz++%2).'"><img src = "game_thumbnails/'.$new_game_id.'/_thumb_100x100.png" class = "game_img"></div>';
}
It would make more sense to add the class to the row, to output the table rows in PHP, use something like this:
<?php for ($i = 0; $rows[$i]; $i ++): ?>
<tr class="<?php echo $i % 2 ? 'odd' : 'even'; ?>">
<td>
<div />
</td>
<td>
<div />
</td>
<td>
<div />
</td>
</tr>
<?php endfor; ?>
The modulo operator % will return the remainder of the division, in this case the division is by two and any equal number will give a remainder of zero, and any unequal number will give a remainder of one.
The selector for the div would then be:
tr.odd td > div
tr.even td > div
this will make sure that only the top div in each row is selected.
UPDATE:
From the code you've supplied it doesn't really appear you're using a table at all (maybe you meant it in a looser sense than the actual HTML element?). Going by your code you already use the modulo in the way described above, but you need to change the following.
$xyz = 0;
$get_new_games = mysql_query("SELECT game_title,game_description,id from games ORDER BY added_date LIMIT 10");
while ($row = mysql_fetch_array($get_new_games)) {
$new_game_title = $row['game_title'];
$new_game_description = $row['game_description'];
$new_game_id = $row['id'];
$new_games_display .= '<div class = "game_module class-'.($xyz++%2 ? 'odd' : 'even').'"><img src = "game_thumbnails/'.$new_game_id.'/_thumb_100x100.png" class = "game_img"></div>';
}
I've added the first line to initialize the variable to zero and changed the $new_games_display-line to ($xyz++%2 ? 'odd' : 'even'). This will ensure that every other div has the class class-odd and the rest class-even.
The only issue I'm having is that the code you supplied doesn't really correspond to your initial problem, with rows of three divs, maybe I'm missing something -- feel free to supply more code and I'll be able to help you more.
While looping through and printing out the rows, you will use the index to determine even or odd.
if(!$index%2){
echo "even";
}
else{
echo "odd";
}
The % is the modulus operator, which returns the remainder when its operands are divided.
Edit:
So in your case, your last line would be
$new_games_display .= '<div class = "game_module class-'.(($xyz++%2) ? 'odd' : 'even').'"><img src = "game_thumbnails/'.$new_game_id.'/_thumb_100x100.png" class = "game_img"></div>';
try some thing like this:
$i = 0;
while ($row = mysql_fetch_array($get_new_games))
{
...
$i++;
$class = ($i%2)? "even" : "odd";
$new_games_display .= '<div class = "game_module class-' . $class .'"><img src = "game_thumbnails/'.$new_game_id.'/_thumb_100x100.png" class = "game_img"></div>';
}
instead of check $i%2 ==0 or not you can use something like
$class = ($i & 1) ? "odd" : "even";
or
if($i & 1){
$class = "odd";
}else{
$class = "even";
}
Your code is only highlighting every other row instead of groups of three rows. You could use an :nth-child css selector, but using php will ensure browser compatibility since the class is hard coded. Anyway..
$evenodd = false; // false indicates odd
$count = 0;
while (...) {
... //display
$count++;
if ($count == 2) {
$evenodd = !$evenodd;
$count = 0;
}
}

New row if a number of cells have been reached

I'm trying to make a table of iframes (2 per row) and I query everything, but whenever it prints, everything is on a row of it's own even though I only tell every second one to. I can't figure out why this is happening:
<div id="main" style="width:1000px;">
<?php
$query = "SELECT * FROM scripts";
mysql_connect("localhost", "root", "");
mysql_select_db("scriptsearch");
$results = mysql_query($query);
$num = mysql_num_rows($results);
mysql_close();
?>
<table border="0">
<?php
for($i = 0; $i <= $num; $i++){
if($i % 2 == 0) //is this the second one? if so, make a new row
echo '<tr>';
else{
?>
<td><iframe src="scriptpreview.php?id=<?php echo $i;?>" style="width: 350px; height: 230px;" frameBorder="0" scrolling="no">Your browser needs to support iFrames for this website.</iframe></td>
<?php }if($i % 2 == 0) echo '</tr>';/*end the row*/ } ?>
</table>
</div>`
Edit: I've tried Krynble's solution, but no matter how I modify it, it still doesn't show up how I expect.
There's an error in your loop.
Try this:
<?php
for($i = 0; $i <= $num; $i++){
if($i % 2 == 0) //is this the second one? if so, make a new row
echo '<tr>';
?>
<td><iframe src="scriptpreview.php?id=<?php echo $i;?>" style="width: 350px; height: 230px;" frameBorder="0" scrolling="no">Your browser needs to support iFrames for this website.</iframe></td>
<?php if($i % 2 == 1) echo '</tr>';/*end the row*/ } ?>
<?php if($i % 2 == 1) //close last row in case we haven't done it yet.
echo '</tr>';?>
You should print the iframe unconditionally, not inside an else. Besides, the closing </tr> should be printed when $i is odd.
Other people have commented on the php/html part, let me focus on the query part:
Don't do this:
$query = "SELECT * FROM scripts"; (1) select all ?
mysql_connect("localhost", "root", ""); (3) don't connect as root!
mysql_select_db("scriptsearch");
$results = mysql_query($query); (4) no check for errors?
$num = mysql_num_rows($results); (2) when you only want 1 count?
Do this instead:
$query = "SELECT count(*) as rowcount FROM scripts";
mysql_connect("localhost", "user1", "password");
mysql_select_db("scriptsearch");
if ($results = mysql_query($query)) {
$row = mysql_fetch_row($results);
$num = $row['rowcount'];
} else { echo "error....." }
You don't have an opening <tr> tag in your table. You need to have a table row before you can put data in it.

how do I alternate the float on consecutive database entires?

My Website
As you can see on the above link there are several 'kids', the information for each one is grabbed from a database.
I want to make each alternating image float to the left, so that the images go left, then right, then left etc. At the moment they all float left. This is what I have so far:
<?php
$query="SELECT id, title, text, media, media2, thumb, deleted FROM kids ORDER BY id DESC";
$result=mysql_query($query);
while($row = mysql_fetch_array($result)){
if($row['deleted'] == 0) {
echo '<div id="'.$row['title'].'">';
echo '<img src="images/'.$row['media'].'" class="floatLeftClear" id="border" />';
if($row['media2'] != "") {
echo '<img src="images/'.$row['media2'].'" class="floatLeftClear" id="border" />';
}
echo '<p id="text">';
echo '<span class="kisstitle">'.$row['title'].'</span><br>';
echo $row['text'];
echo '</p>';
echo ' <p align="center" id="spererater"><img src="images/seperater.jpg" width="900" height="5" />Top<br /></p>';
}}
?>
I tried to check the ID, if even, float left, if odd, float right, but I couldn't work out how to do it, plus the ID may not always be even / odd alternating so I'd rather find a different solution if possible.
Use a counter variable, increment by one each time you're looping over an item -- and use that counter with a modulo, to determiner whether you are on an even or odd line :
$counter = 0;
while($row = mysql_fetch_array($result)){
if (($counter % 2) == 0) {
// even
} else {
// odd
}
// use the data of the current $row, display it
$counter++; // increment the counter, for next iterator
}
Add a counter. Before loop $i = 0; and inside loop $i++, if ($i % 2 == 0) { // odd} else {// even}

Categories