how to control this foreach loop - php

i use this foreach to build youtube video gallery but i want to display 3 videos for each line..so how to specify to loop 3 times and then move to the next line and loop 3 times...
i dont need to build all loops in one line..
thanks for helping
table id="tblThumbsLayout" cellpadding="0" cellspacing="6">
<tr>
<?php foreach ($vcats as $vcat) { ?>
<td class="tdImg">
<div>
<?php echo '<iframe class="youtube-player" type="text/html" width=" 200 " height=" 100 " src="http://www.youtube.com/embed/' . $vcat['Video']['link'] . '"></iframe>' ;?>
<div class="text"><?php echo '<b>'. $vcat['Video']['title'].'</b>' ; ?></div>
</div>
</td>
<?php } ?>
</tr>
</table>

Try this:
<?php
$i = 1;
foreach ($vcats as $vcat) {
if($i%3 == 0){
echo "</tr><tr>";
}
?>
<td class="tdImg">
<div>
<?php echo '<iframe class="youtube-player" type="text/html" width=" 200 " height=" 100 " src="http://www.youtube.com/embed/' . $vcat['Video']['link'] . '"></iframe>' ;?>
<div class="text"><?php echo '<b>'. $vcat['Video']['title'].'</b>' ; ?></div>
</div>
</td>
<?php $i++; } ?>

I would add a div id=video to each item and in the style sheet for that div id #video use display: inline;
Then set the width of the div to allow 3 per row.
This way you don't have to worry too much about the loop.

<table id="tblThumbsLayout" cellpadding="0" cellspacing="6">
<tr>
<?php $counter = 1; $last = count($vcats)-1; ?>
<?php foreach ($vcats as $vcat) { ?>
<td class="tdImg">
<div>
<?php echo '<iframe class="youtube-player" type="text/html" width=" 200 " height=" 100 " src="http://www.youtube.com/embed/' . $vcat['Video']['link'] . '"></iframe>' ;?>
<div class="text"><?php echo '<b>'. $vcat['Video']['title'].'</b>' ; ?></div>
</div>
<?php if($counter%3==0 && $counter != $last): ?>
<br>
<?php $counter++; ?>
<?php endif; ?>
</td>
<?php } ?>
</tr>
</table>

Keep a count of the loop iterations. Then using the modulus operator, check whether this iteration divided by 3 has a remainder of 0. If it does, then add a break line or new table row to move onto the next line.
Like so:
<table id="tblThumbsLayout" cellpadding="0" cellspacing="6">
<tr>
<?php
$counter = 1;
foreach ($vcats as $vcat) {
?>
<td class="tdImg">
<div>
<?php echo '<iframe class="youtube-player" type="text/html" width=" 200 " height=" 100 " src="http://www.youtube.com/embed/' . $vcat['Video']['link'] . '"></iframe>' ;?>
<div class="text"><?php echo '<b>'. $vcat['Video']['title'].'</b>' ; ?></div>
</div>
</td>
<?php
if($counter % 3 == 0){
echo '<br/>';
}
++$counter;
}
?>
</tr>
</table>

Related

PHP looping in table

I'm trying create loop in my table, there is 4 item, when column is 3 then create new row . The current output is like this:
x
x
x
x
Here's my code:
<table border="0">
<?php
$i = 0;
foreach ($list_items as $item){ // there is 4 item
$i++;
echo "<tr>";
if ($i <= 3) { ?>
<td class="text-center" style="width:83.14px; height:60.47px; font-size:0.6em">
<?php echo $item['productId'] ?>
<br>
<br>
<?php echo $item['qty'] ?>
</td>
<?php }
}
echo "</tr>";
?>
</table>
What i expected is like this:
x|x|x
x
Thank you.
In the comment section of your question, Sirko is right.
Anyway you can do this like below;
<?php
$i = 0;
foreach ($list_items as $item) {
if($i % 3 == 0)
echo '<tr>';
echo '<td> bla bla bla </td>';
if($i % 3 == 0)
echo '</tr>';
$i++;
}
Change your code to below, it should work.
<table border="0">
<?php
$i = 0;
foreach ($list_items as $item){ // there is 4 item
$i++;
echo "<tr>";
if($i%3==0) echo echo "</tr><tr>";
?>
<td class="text-center" style="width:83.14px; height:60.47px; font-size:0.6em">
<?php echo $item['productId'] ?>
</td>
<td>
<?php echo $item['qty'] ?>
</td>
<?php
}
if($i%3!=0)
echo "</tr>";
?>
</table>
use array_chunk()
<?php
foreach (array_chunk($list_items,3) as $items) {
echo '<tr>';
foreach($items as $item){
?>
<td class="text-center" style="width:83.14px; height:60.47px; font-size:0.6em">
<?php echo $item['productId'] ?>
<br>
<br>
<?php echo $item['qty'] ?>
</td>
<?php
}
echo '</tr>';
}
?>
try this ==>
<table border="0">
<?php
$i = 0;
foreach ($list_items as $item) { // there is 4 item
if ($i % 3 == 0) // for i=0,3,6,9 <tr> tag will open
echo "<tr>";
?>
<td class="text-center" style="width:83.14px; height:60.47px; font-size:0.6em">
<?php echo $item['productId'] ?>
<br>
<br>
<?php echo $item['qty'] ?>
</td>
<?php
if ($i % 3 == 0) // for i=0,3,6,9 <tr> tag will close
echo "</tr>";
$i++;
}
?>
</table>

fetch data in rows/column using php

I want to make 4 columns in table. In code all the images are comes in single row and single column. But I want a single row containing 4 columns with 4 images (images fetching from database), then create another row and automatically add next 4 images & so on. I don't know how I do this can anyone please suggest me how I do this.
<form name="form">
<select id="sorting" style="width:140px" onChange="optionCheck()">
<option id="s">---Sort By----</option>
<option value="bydate">Sort By Date</option>
<option value="bytopic">Sort By Topic</option>
</select>
</form>
<br />
</div>
<?php include 'connection.php'; ?>
<div id="showByDefault">
<table style="width:60%">
<tr>
<?php include 'connection.php'; ?>
<div id="showByDefault">
<!--<table style="width:60%"><tr>-->
<?php
$sql1=mysqli_query($con,"select * from `insert-n-retrive-pdf` ORDER BY date DESC") or die(mysqli_error($con));
$i=0;
echo "<table><tr>";
while($row=mysqli_fetch_array($sql1))
{
if($i != 0 && $i%4 == 0) {
echo '<tr></tr>';
}
?> <td style="padding:20px;">
<img src="<?php echo $row["thumbnails"]; ?>" /></td><?php
echo '</tr>';
$i++;
}
?></tr></table>
</div>
<div id="hideall">
<div id="topic1">
<?php include 'pdf-sort-by-topic.php'; ?>
</div>
<div id="topic">
<?php include 'pdf-sort-by-date.php'; ?>
</div>
</div>
Try this one 100% working: Nice and easy.
<?php
$sql1=mysqli_query($con,"select * from `insert-n-retrive-pdf` ORDER BY date DESC") or die(mysqli_error($con));
$i = 0;
echo "<tr>";
while($row=mysqli_fetch_array($sql1)) {
if($i != 0 && $i%4 == 0) {
echo "</tr><tr>";
}
?>
<td style="padding:20px;"><img src="<?php echo $row["thumbnails"]; ?>" /></td>
<?php
$i++;
}
?>
Hope this helps!
You can try this code
$query = mysql_query("SELECT * FROM insert-n-retrive-pdf ORDER BY date DESC");
echo '<table width="960">';
$i = 0; //first, i set a counter
while($fetch = mysql_fetch_assoc($query)){
//counter is zero then we are start new row
if ($i==0){
echo '<tr>';
}
//here we creating normal cells <td></td>
$image_name = $fetch['thumbnails'];
$image_location = $fetch['path'];
echo '<td>'.'<img src="'.$image_location.'" alt="'.$image_name.'"/>'.'</td>';
//there is a magic - if our counter is greater then 4 we set counter to zero and close tr tag
if ($i>4){
$i=0;
echo '</tr>';
};
$i++; //$i = $i + 1 - counter + 1
}
echo '</table>';
You can fetch all your images into one-dimensional array and then use function array_chunk(). It will split an array into smaller parts you need. Here's a manual page.
Actually, You can get something like this:
<?php
$images = array();
while($row=mysqli_fetch_array($sql1))
{
$images[] = $row;
}
$images = array_chunk($images, 4);
?>
<?php foreach($images as $imagesChunk): ?>
<tr>
<?php foreach ($imagesChunk as $image): ?>
<td style="padding:20px;">
<a href="<?=$image["path"];?>" target="_blank">
<img src="<?=$image["thumbnails"];?>" />
</a>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
<table style="width:60%">
<tr>
<?php
$counter = 0;
$sql1 = mysqli_query($con, "select * from `insert-n-retrive-pdf` ORDER BY date DESC"
) or die(mysqli_error($con));
while($row=mysqli_fetch_array($sql1))
{
?>
<td style="padding:20px;">
<a href="<?php echo $row["path"]; ?>" target="_blank">
<img src="<?php echo $row["thumbnails"]; ?>" />
</a>
</td>
<?php
if($counter == 4)
{
echo "</tr>";
echo "<tr>";
$counter = 0;
}
$counter++;
}
?>
</tr>
</table>

Make 4 columns in my while loop

Below is my while loop table, currently it's showing just one item per row. I can't seem to figure out how to get 4 items/columns to show before it shows a new row below. Any help with this would be much appreciated, thank you!
Jerome
<table style="background-color: white">
<?php
while ($row = mysql_fetch_array($rs)) {
?>
Collapse | Copy Code
<tr <?php //if ($i % 2) echo ' style="background-color: #ECECFB;"';?>>
<td class="rows"><font color="4D4D4D" size="3"><? echo '<a type="video/x-matroska" href=file://///'.$row["Link"].' target=blank>'.$row["Name"].'</a>' ?><br />
<? echo '<a type="video/x-matroska" href=file://///'.$row["Link"].' target=blank><img src='.$row["Picture"].' height=210px width=141px></a>' ?><br />
<? echo '('.$row["Type"].')' ?> <? echo $row["Year"] ?> <? echo $row["Rating"] ?> <? echo date('H:i', mktime(0,$row["Length"])); ?><br />
<? echo $row["Genre"] ?><br />
<? if ($row["Queue"]==='x') {
echo
"<center><a title=Remove From Watch List href='deletequeue.php?id=".$row['ID']."'><img align='center' width='20px' src='http://www.ourlittlelucas.net/ourflix/images/Minus.png'></a></td></font></center>";
}
else {
echo "<center><a title=Add To Watch List href='addqueue.php?id=".$row['ID']."'><img align='center' width='20px' src='http://www.ourlittlelucas.net/ourflix/images/Plus.png'></a></td></font></center>";
}
?>
</td></tr></font>
<?php $i++?>
<?php
}
?>
</table>
Try it
<table style="background-color: white">
<?php
while ($row = mysql_fetch_array($rs))
{
?>
Collapse | Copy Code
<tr <?php //if ($i % 2) echo ' style="background-color: #ECECFB;"';?>>
<td class="rows">
<font color="4D4D4D" size="3"><?php echo '<a type="video/x-matroska" href=file://///'.$row["Link"].' target=blank>'.$row["Name"].'</a>'; ?><br />
<?php echo '<a type="video/x-matroska" href=file://///'.$row["Link"].' target=blank><img src='.$row["Picture"].' height=210px width=141px></a>'; ?><br />
<?php echo '('.$row["Type"].')' ?>
<?php echo $row["Year"] ;?>
<?php echo $row["Rating"]; ?>
<?php echo date('H:i', mktime(0,$row["Length"])); ?><br />
<?php echo $row["Genre"] ;?><br />
<?php
if ($row["Queue"]=="x") {
echo
"<center><a title=Remove From Watch List href='deletequeue.php?id=".$row['ID']."'><img align='center' width='20px' src='http://www.ourlittlelucas.net/ourflix/images/Minus.png'></a></td></font></center>";
}
else
{
echo "<center><a title=Add To Watch List href='addqueue.php?id=".$row['ID']."'><img align='center' width='20px' src='http://www.ourlittlelucas.net/ourflix/images/Plus.png'></a></td></font></center>";
}
?>
</td></tr></font>
<?php $i++?>
<?php
}
?>
</table>

iterate a html table of two row and 3 column using one php query

I have a database table and that table has 6 rows. What I want is to display that 6 rows in a html page using a 3 column and 2 row table.
I know how to work with php arrays and while loops. My problem is how to limit the array to put 3 items in the first row and put the other 3 in the next row.
this is what i have tried but didn't work
<div id="maincontent">
<!-- class one -->
<?php
$getSection = getSection();
$i=0;
while($allSection = mysql_fetch_array($getSection)){
?>
<div class="subconent">
<table width="937" border="0">
<tr>
<td>
<div class="sub_image">
<img src="admin/uploads/fron_sect/<?php echo $allSection['image']; ?>" width="134" height="120" border="0" alt="HNA" class="PopBoxImageLink" onmouseover="PopEx(this,-50,-25,205,186,20,null);" onclick="window.location='http://localhost/hants/section.php?id=<?php echo urlencode($allSection['id']); ?>'" />
</div>
<div class="cont_txt">
<h3><?php echo $allSection['name_full']; ?></h3>
<p><?php echo substr($allSection['description'],0,140) . ""; ?></p>
<br />
<img src="images/read_more.jpg" alt="Read More" width="89" height="25" border="0" />
</div>
</td>
</tr>
</table>
</div>
<?php
if($i==4) { ?>
<table width="937" border="0">
<tr>
<td> </td>
<td> </td>
<td> </td></tr>
<tr><div class="sub_image">
<img src="admin/uploads/fron_sect/<?php echo $allSection['image']; ?>" width="134" height="120" border="0" alt="HNA" class="PopBoxImageLink" onmouseover="PopEx(this,-50,-25,205,186,20,null);" onclick="window.location='http://localhost/hants/section.php?id=<?php echo urlencode($allSection['id']); ?>'" />
</div>
<div class="cont_txt">
<h3><?php echo $allSection['name_full']; ?></h3>
<p><?php echo substr($allSection['description'],0,140) . ""; ?></p>
<br />
<img src="images/read_more.jpg" alt="Read More" width="89" height="25" border="0" />
</div><td>
<?php }
} ?>
</div>
Use modulo operator (%):
http://www.devchunks.com/web-development/using-the-php-modulus-operator/
something like this:
<table>
<?php
$i = 0;
while ( $row = mysql_fetch_array($result) ){
if ($i % 3 == 0){
echo '<tr>';
}
echo '<td>'.$row['column_name'].'</td>';
if ($i % 3 == 2){
echo '</tr>';
}
$i++;
}
//here is a check in case you don't have multiple of 3 rows
if ($i % 3 != 0){
echo '</tr>';
}
?>
</table>
At its base, you'll need something like this:
<table>
<tr>
<?
$count = 0;
foreach ($row) {
echo "<td>" . $row["value"] ."</td>";
$count++;
if (($count % 3) == 0) && ($count > 0) {
echo ("</tr><tr>");
}
}
?>
</tr>
</table>
Start printing out the header of your table, and then begin iterating through the dataset. Keep track of how many you've printed out, and if this is the third one, print the HTML to finish this row and start the next one. (I've used %, so it'll wrap on every third entry, not just the first one)
Well, you could correctly fetch those informations in your sql-query ( just one example that could fit http://en.wikibooks.org/wiki/MySQL/Pivot_table ).
Or simply fetch everything into PHP arrays.
Oldschool: mysql_query() and while( $row = mysql_fetch_array() )
Newchool: PDO ( http://de.php.net/manual/en/book.pdo.php )
Awesome! Thanks a lot. It works for me, Zend. You can try something like this.
<table width="1024px" border="0" cellspacing="2" cellpadding="2">
<?php
$i = 0;
foreach ($this->rows as $row )
{
$img = IMAGE_PATH . '/' . 'gallery/' . $row->gly_thumbnail;
if ($i % 3 == 0)
{
echo '<tr>';
}
?>
<td align="center">
<img src="<?php echo $img; ?>" width="300" height="215"><br/>
<?php echo $row->gly_title; ?>
</td>
<?php
if ($i % 3 == 2)
{
echo '</tr>';
}
$i++;
}
//here is a check in case you don't have multiple of 3 rows
if ($i % 3 != 0)
{
echo '</tr>';
}
?>
</table>
<?php if ($i++%$_columnCount==0): ?>
<tr>
<?php endif ?>
<td> <img src="<?php echo site_url('uploads/shelter_images/'.$row->shelter_id."/".$img->imagefile) ?>" alt="" width="300" ></td>
<?php if ($i%$_columnCount==0 || $i==$totalImg): ?>
</tr>
<?php endif; ?>
<?php } ?>

PHP Mysql Image Display

I'm working on a php gallery. I'm displaying image from mysql db using php, but my images are displaying in one by one. which means the first image in first row and second image in second row. but I want to display my image as 3 or 4 per row. what coding changes can I make. my php code as shown below.
<?php
include_once("config.php");
$result=mysql_query("SELECT * FROM images");
while($res=mysql_fetch_array($result)){ ?>
<table width='200'>
<tr>
<td><?php echo"<a href='indimage.php?imageid=$res[imageid]'>"?><?php echo $res['imagename']?><?php echo"</a>"?></td>
</tr>
<tr>
<td>
<div id="news-image">
<?php echo"<a href='indimage.php?imageid=$res[imageid]'>"?>
<?php echo'<img src='.$res['image'].' width="250" height="100">'?><?php echo"</a>"?>
</div>
</td>
</tr>
</table>
<?php } ?>
array_chunk() is a function to split an array into a collection of X items for you to loop through without having to keep counters (you can then use array_pad() on the last item in the list if you need padding)
if($array = array_chunk(mysql_fetch_assoc($result),4))
{
foreach($array as $row)
{
echo '<div class="row">';
foreach($row as $col)
{
echo '<div class="item">' . $col['image'] . '</div>';
}
echo '</div>';
}
}
You're outputting a table per image. At minimum, your code should be more like this:
<table>
<tr>
<?php while($res etc...) { ?>
<td>
<img src="<?php echo ......?>" />
</td>
<?php } ?>
</tr>
</table>
Now you'll get all the images in a single row of a single table. Making it have multiple rows is left as an exercise to the OP.
follow this example
<table>
<tr>
<?php
$i = 1;
do{
echo "<td>" . $i . "</td>";
//Num of Columns
if( $i%3 == 0 ){
echo "</tr><tr>";
}
$i++;
}while($i<=10);
?>
</tr>
<table>
will return the result something like you want..
<?php
include_once("config.php");
$result=mysql_query("SELECT * FROM images");
?>
<table>
<tr>
<?php
$cnt = 0;
while($res=mysql_fetch_array($result))
{
if($cnt == 3){
echo "</tr><tr>";
}
?>
<td>
<table width='200'>
<tr>
<td><?php echo"<a href='indimage.php?imageid=$res[imageid]'>"?><?php echo $res['imagename']?><?php echo"</a>"?></td>
</tr>
<tr>
<td>
<div id="news-image">
<?php echo"<a href='indimage.php?imageid=$res[imageid]'>"?>
<?php echo'<img src='.$res['image'].' width="250" height="100">'?><?php echo"</a>"?>
</div>
</td>
</tr>
</table>
</td>
<?php
$cnt++;
}
?>
</tr>
</table>
Use the following code.
<?php
include_once("config.php");
$result=mysql_query("SELECT * FROM images");
?>
<table>
<tr>
<?
$varcount=0;
while($res=mysql_fetch_array($result))
{
$varcount++;
if($varcount == 4) // Count of images per row. 3 or 4
{
$varcount=0;
?>
</tr><tr>
<?
}
?>
<td>
<table width='200'>
<tr>
<td><?php echo"<a href='indimage.php?imageid=$res[imageid]'>"?><?php echo $res['imagename']?><?php echo"</a>"?></td>
</tr>
<tr>
<td>
<div id="news-image">
<?php echo"<a href='indimage.php?imageid=$res[imageid]'>"?>
<?php echo'<img src='.$res['image'].' width="250" height="100">'?><?php echo"</a>"?>
</div>
</td>
</tr>
</table>
</td>
<?php
}
?>
</tr>
</table>
You could instead output the images as a list of divs, or just divs, and then use CSS to show the images in two columns. Your layout should not be that hardwired.
<style>
div.gallery {
width: 650px;
}
div.gallery ul li {
list-style: none;
float: left;
}
div.image {
height: 500px;
width: 300px;
}
</style>
<div class="gallery">
<ul>
<li>
<div class="image">
<span class="image_title">Some title</span><br/>
<img src="foo.png"/>
</div>
</li>
<li>
<div class="image">
<span class="image_title">Another title</span><br/>
<img src="bar.png"/>
</div>
</li>
<li>
<div class="image">
<span class="image_title">Another title</span><br/>
<img src="foo.png"/>
</div>
</li>
<li>
<div class="image">
<span class="image_title">Another title</span><br/>
<img src="bar.png"/>
</div>
</li>
<li>
<div class="image">
<span class="image_title">Another title</span><br/>
<img src="foo.png"/>
</div>
</li>
</ul>
</div>
Result:
Your code should look something like:
<div class="gallery">
<ul>
<?php
include_once("config.php");
$result = mysql_query("SELECT * FROM images");
while($res = mysql_fetch_array($result)) {
?>
<li>
<div class="image">
<a class="image_title" href="indimage.php?imageid=<?php echo $res['imageid']?>"><?php echo $res['imagename']?></a><br/>
<img src="<?php echo $res['image']?>" />
</div>
</li>
<?php
}
?>
</ul>
</div>
Here is the Solution i think you want that:
there are three pages.
1. index.php (which has the form for uploading the image)
2. upload.php (which save the image in directory and its path in database)
3. showimage.php (Finally, which will show the image)
here is the code
(index.php)
<form method="post" action="upload.php" enctype="multipart/form-data">
<label>Choose File to Upload:</label><br />
<input type="hidden" name="id" />
<input type="file" name="uploadimage" /><br />
<input type="submit" value="upload" />
</form>
(upload.php)
<?php
$target_Folder = "upload/"; // directory where images will be saved
$target_Path = $target_Folder.basename( $_FILES['uploadimage']['name'] );
$savepath = $target_Path.basename( $_FILES['uploadimage']['name'] );
$file_name = $_FILES['uploadimage']['name'];
if(file_exists('upload/'.$file_name))
{
echo "That File Already Exisit";
}
else
{
// Database
$con=mysqli_connect("localhost","user_name","pasword","database"); // Change it if required
//Check Connection
if(mysqli_connect_errno())
{
echo "Failed to connect to database" . mysqli_connect_errno();
}
$sql = "INSERT INTO image (id,image, image_name)
VALUES ('$uid','$target_Folder$file_name','$file_name') ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added successfully in the database";
echo '<br />';
mysqli_close($con);
// Move the file into UPLOAD folder
move_uploaded_file( $_FILES['uploadimage']['tmp_name'], $target_Path );
echo "File Uploaded <br />";
echo 'File Successfully Uploaded to: ' . $target_Path;
echo '<br />';
echo 'File Name: ' . $_FILES['uploadimage']['name'];
echo'<br />';
echo 'File Type: ' . $_FILES['uploadimage']['type'];
echo'<br />';
echo 'File Size: ' . $_FILES['uploadimage']['size'];
}
?>
Show Image
(showimage.php)
<?php
$con=mysqli_connect("localhost","user_name","password","database_name"); // Change it if required
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM image " );
while($row = mysqli_fetch_array($result))
{
echo '<img src="' . $row['image'] . '" width="200" />';
echo'<br /><br />';
}
mysqli_close($con);
?>
Features
It will check the names of file if that name file already exisit it will not uplad the file and alert the user.
Database Structure
id int(4) Auto Increment - image varchar(100) - image_name varchar(50)

Categories