How to restrict number of images in a row to three? - php

I am populating the images from my database in a table, how to restrict the images to three per row?
<table border="0" align="center" height="25%" width="25%" >
<tr><td align="center" width="50px" bgcolor="#4b2d0e"><strong><font color="#FFFFFF">Friend List</font></strong></td></tr>
<? foreach($Selected as $row)
{
$value = $row['dPath'];
$imgp = base_url()."images"."/".$value;
?>
<tr><td bgcolor="#999999">
<strong ><?=$row['dFrindName'].'</br>';?></strong>
<? if($value!="") { ?>
<a class="Tab_Link" href="<? echo site_url();?>/friends/View_FProfile/<?=$row['dMember_Id']?>"><img src="<?=$imgp ?>" name="b1" width="90" height="80" border="0"/></a><br>
<? } else { ?>
<a class="Tab_Link" href="<? echo site_url();?>/friends/View_FProfile/<?=$row['dMember_Id']?>"><img src="../images/us.png" width="90px" height="80px"></a>
<? }?>
</td></tr>
<? }}?>
</table>
This is my table

<?php
$x=0;
foreach($Selected as $row){
if($x%3 == 0)
echo '<tr>';
$value = $row['dPath'];
$imgp = base_url()."images"."/".$value;
?>
<td style="background-color:#999999;">
<strong ><?=$row['dFrindName'].'</br>';?></strong>
<?php if($value!="") {?>
<a class="Tab_Link" href="<? echo site_url();?>/friends/View_FProfile/<?=$row['dMember_Id']?>"><img src="<?=$imgp ?>" name="b1" width="90" height="80" border="0"/></a><br>
<?php } else { ?>
<a class="Tab_Link" href="<? echo site_url();?>/friends/View_FProfile/<?=$row['dMember_Id']?>"><img src="../images/us.png" width="90px" height="80px"></a>
<?php }?>
</td>
<?php
if($x%3 == 0)
echo '</tr>';
x++;
}
if(($x-1)%3 != 0)
echo '</tr>'; //Prints out the last '<tr>' if one isn't printed.
?>
You need to use an if with a modulus operator.

Here, I cleaned up your invalid HTML, used CSS, and used a more recommended PHP coding style.
Please note: you need to be aware that if $Selected contains user-inputted (or otherwise non-HTML-safe) data, you need to wrap your output in htmlspecialchars or be open to XSS vulnerabilities.
It was a little unclear what you meant by wanting to "restrict the images to three per row" considering that it was only showing 1 per row currently. If I am to assume that you want to show 3 per row rather than 1, than you need to use the modulus operator and only open a new <tr> after every third element, and then close it at the right time. Like this:
<style type="text/css">
a img { border: none; }
.friend-list { border: none; width: 25%; height: 25%; margin: 0 auto; }
.friend-list th { text-align: center; background-color: #4b2d0e; color: #fff; font-weight: bold; }
.friend-list td { background-color: #999999; }
</style>
<?php
$numCols = 3;
$colCount = -1;
?>
<table class="friend-list">
<tr>
<th colspan="<?php echo $numCols; ?>">Friend List</th>
</tr>
<?php
foreach($Selected as $row) {
$value = $row['dPath'];
$imgp = ($value) ? base_url().'images/'.$value : '../images/us.png';
if(++$colCount % $numCols == 0) {
echo '<tr>';
}
?>
<td>
<strong><?php echo $row['dFriendName']; ?></strong><br />
<a class="Tab_Link" href="<?php echo site_url(); ?>/friends/View_FProfile/<?php echo $row['dMember_Id']; ?>">
<img src="<?php echo $imgp; ?>" width="90" height="80" />
</a>
</td>
<?php
if(($colCount + 1) % $numCols == 0) {
echo '</tr>';
} elseif (($colCount + 1) == count($Selected)) {
// if 16 elements are to fit in 3 columns, print 2 empty <td>s before closing <tr>
$extraTDs = $numCols - (($colCount + 1) % $numCols);
for ($i = 0; $i < $extraTDs; $i++) {
echo '<td> </td>';
}
echo '</tr>';
}
}
?>
</table>

Tables should be reserved for situations where columns and rows have meaning... A better solution is to use floated block elements instead of table cells. When you float a bunch of similar blocks, they wrap automatically, so the key is making their parent container just wide enough to hold 3 of them.
You don't need to do anything special with php to create new rows, so i'll just display the html and css, letting you write the php to make it happen.
html:
<div id="replacesTable">
<div class="replacesTableCell">
<div class="name">Name</div>
<img src="http://stackoverflow.com/favicon.ico" />
</div>
<div class="replacesTableCell">
<div class="name">Name</div>
<img src="http://stackoverflow.com/favicon.ico" />
</div>
<div class="replacesTableCell">
<div class="name">Name</div>
<img src="http://stackoverflow.com/favicon.ico" />
</div>
<div class="replacesTableCell">
<div class="name">Name</div>
<img src="http://stackoverflow.com/favicon.ico" />
</div>
<div class="clear"> </div>
</div>
css:
#replacesTable{
width: 300px;
}
div.replacesTableCell{
float:left;
width: 100px;
/* styles below are just to make it easier to see what's happening */
text-align:center;
font-size: 10px;
margin: 20px 0;
}
/* this just stretches the parent container #replacesTable around the entries*/
.clear{
clear:both;
height:1px;
overflow:hidden;
}

You can use CSS as an alernative if the images are of a fixed width and you can do without the tables - create a wrapper div with a fixed width around your entire image list, and simply float each image left.

Here is a simplified example without the extraneous styling information to show the principal. Every 3rd image we want to write the opening and closing tags (though not at the same time).
So we loop through the list of images and use the moduulus operator to know when we should print the <tr> tags.
<?php
$column_count = 3;
$image_list = get_images();
?>
<table>
<?php
for($i=0; $i < sizeof($image_list); i++) {
$cur_img = $image_list[$i];
$img_url = $cur_img['url'];
// open a we row every 3rd column
if($i % $column_count == 0) {
print '<tr>';
}
// for every image we want a table cell, and an image tag
print "<td> <img src='$img_url'> </td>";
// close the row every 3rd column, but offset by 3 from the opening tag
if($i % $column_count == $column_count - 1) {
print '<tr>';
}
}
// what if the number of images are not div by 3? Then there will be less
// than 3 items in the last row, and no closing tag. So we look for that and
// print a closing tag here if needed
if(sizeof($image_list) % $column_count != 0) {
print '</tr>';
}
?>
</table>

You can try using http://www.php.net/manual/en/function.array-chunk.php

Hey, would you try this.
Notice that I replaced the if...else with a ternary operator. I prefer it compact.
Hope it helps you and anyone else interested.:)
<table border="0" align="center" height="25%" width="25%" >
<tr>
<td colspan="3" align="center" width="50px" bgcolor="#4b2d0e">
<strong><font color="#FFFFFF">Friend List</font></strong>
</td>
</tr>
<?
$imgs=0;
foreach($Selected as $row){
$value = $row['dPath'];
$imgp = base_url()."images"."/".$value;
if($imgs%3 == 0){
echo '<tr>';
}
?>
<td bgcolor="#999999">
<strong ><?=$row['dFrindName'].'</br>';?></strong><a class="Tab_Link" href="<? echo site_url();?>/friends/View_FProfile/<?=$row['dMember_Id']?>"><img src="<?=$value!=""? $imgp: '../images/us.png' ?>" name="b1" width="90" height="80" border="0"/></a>
</td>
<?
$imgs++;
if($imgs%3 == 0){
echo "</tr>\n";
}
}//end loop
echo '</tr>';//end last row
?>
</table>

Related

PHP - How to create 4 columns (4 x 25%) and then end the line with a new column of 4

I have a project going on where we are able to create a product, which is loaded to the front page in PHP.
However, if there are 5 products, then it won't create a new line. What should happen if there are 5 products is 2 lines of 4 each should be displayed.
<section class="ICO">
<div class="one-fourth-gridtable">
<table class="grid table">
<?php
while ($subject = mysqli_fetch_assoc($subject_set)) {
$imagenavn = $subject['navn'];
$sql = "SELECT * FROM product_images WHERE image_name = '$imagenavn'";
$sth = $db->query($sql);
$result = mysqli_fetch_array($sth);
?>
<td>
<div style="border: 1px solid black; border-radius:2000px;">
<img src="data:image/jpeg;base64,<?= base64_encode($result['image']); ?>" />
</div>
<a class="action" href="<?= url_for('../show.php?id=' . h(u($subject['id']))); ?>"><?php echo h($subject['navn']); ?></a>
</td>
<?php } ?>
</table>
</div>
</section>
I tried to style the table with CSS:
table {
background-color: #6991ac;
width: 100%;
text-align: center;
display: inline-table;
margin-top: -5%;
}
.ICO {
max-width: 1100px;
margin: 0 auto;
}
.one-fourth-gridtable {
width: 100%;
}
With this code you get a new line after 4 images and after 8 images the loops stops because of the $u. You can delete/change the $u if not needed.
<?php require_once('private/initialize.php'); ?>
<?php $test = "Alle Produkter"; ?>
<?php $subject_set = find_all_subjects(); ?>
<?php $page_title = 'Forside'; ?>
<?php include(SHARED_PATH . '/staff_header.php'); ?>
<!--- Start of header --><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="design/Design.css" rel="stylesheet" type="text/css" />
<meta charset="utf-8" />
</head>
<!--- End of header -->
<!--- Start of section (BANNER) -->
<section class="banner">
<div class="banner-inner">
<div id="banner-image"><img src="img/cryptocurrency.png" style="margin-top:10% !important"></div>
</div>
</section>
<!--- End of section (BANNER) -->
<!--- Start of section (ICO'S) -->
<!--- End of section (ICO'S) -->
<div class="sactions">
<!-- <a class="saction" href="<?php echo url_for('/staff/subjects/new.php'); ?>">Create New Subject</a> --> </div>
<section class="ICO">
<div class="one-fourth-gridtable">
<table class="gridtable">
<?php
$i = 0;
$u = 0;
while($subject = mysqli_fetch_assoc($subject_set)) {
$imagenavn = $subject['navn'];
$sql = "SELECT * FROM product_images WHERE image_name = '$imagenavn'";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
$i++;
$u ++;
?>
<td>
<?php
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ). '"/> '; ?>
<a class="action" href="<?php echo url_for('../show.php?id=' . h(u($subject['id']))); ?>"><?php echo h($subject['navn']);?></a>
<?php
if ($u > 7 ) {
break;
}
if ($i > 3) {
echo '</tr><tr>';
$i = 0;
}
?>
</td>
<?php } ?>
</table>
</div>
</section>
<?php
mysqli_free_result($subject_set);
?>
Tables automatically expand to contain all of the elements on a single row.
To get around this, you could simply make use of new table rows (<tr>), though I would recommend swapping to a <div> layout and floating the elements to the left:
<div class="contents">
// output the contents
</div>
.contents img {
float: left;
}
This will cause the elements to automatically move to the next line when occupying more than the available width, with no need to worry about how many elements should be displayed per row:
.contents img {
float: left;
margin: 5px;
}
<div class="contents">
<img src="http://placehold.it/200" />
<img src="http://placehold.it/200" />
<img src="http://placehold.it/200" />
<img src="http://placehold.it/200" />
</div>
Hope this helps! :)
First count the results to display, say $count.
<table class="grid table">
<tr>
<?php
$trer = 1;
$cycler = 0;
while($subject = mysqli_fetch_assoc($subject_set))
{
$cycler++;
$imagenavn = $subject['navn'];
$sql = "SELECT * FROM product_images WHERE image_name = '$imagenavn'";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
?>
<td>YOUR CONTENT</td>
<?php
if($trer == 4 && $cycler < $count) //if true you're at the last td of the line, but not on the last line, so let's put a new line
{
echo "</tr><tr>";
$trer = 0;
}
$trer++;
}
if($trer > 0 && $trer < 4) //if line is incomplete (less than 4 items but 1 or more
{
for(int t = 0; $t < 4 - $trer; $t++) //echo empty TDs till filling the line
echo "<td> </td>";
}
?>
</tr>
</table>

How to enter a word in looping <td> in php

I have table data which is taking data from foreach and looping through a for loop.(looping 3 times with different values from foreach)
I want to know that how can I put a word in last <td> ?
my code;
<?php
foreach($halls_all_array AS $row){?>
<td nowrap class="auto-style34" style="height: 30px; width: 20%" align="left">
time1-<?php echo format_time($row[$start]['time'])?>
</td>
<?php } ?>
foreach($halls_all_array AS $row){
for($j=$start;$j<$limit;$j++){ ?>
<td nowrap class="auto-style34" style="height: 30px; width: 20%" align="left"> time1-<?php echo format_time($row[$j]['time'])
if($j==($limit-1)){ echo "word";}
?>
</td>
<?php
}
}
?>
View
<?php foreach(... ) { ?>
<td>loop td</td>
<?php } ; ?>
Use :
if($j == ($limit - 1)) {
// last <td> here. You can add the text here.
}
EDIT
<?php
$count = count($halls_all_array);
$i = 0;
foreach($halls_all_array AS $row){
?>
<td nowrap class="auto-style34" style="height: 30px; width: 20%" align="left">time1-<?php echo format_time($row[$start]['time'])?>
<?php
if(++$i === $count){
//echo 'WORD TO PRINT';
}
?>
</td>
<?php
}
?>
Try the following
// first of all check $halls_all_array and $start are defined or not
<?php
$count=count($halls_all_array);
$i=1;
foreach($halls_all_array AS $row){
echo'<td nowrap class="auto-style34" style="height: 30px; width: 20%" align="left">time1-'.format_time($row[$start]['time']);
if($i == $count){
//echo 'WORD TO PRINT';
}
echo'</td>';
$i++;
}
?>
Try this code
<?php
$length = count($halls_all_array); // TAKE THE LENGTH OF ARRAY
$i = 1;
foreach($halls_all_array as $row){ ?>
<td nowrap class="auto-style34" style="height: 30px; width: 20%" align="left">
<?php if($i < $length){ ?>
time1- <?php echo format_time($row[$start]['time']);?>
<?php }else{
echo "YOUR WORD..."; // Last Looping..
} ?>
</td>
<?php
$i++; // INCREMENT THE COUNTER
} ?>
first get the last key from array
end($halls_all_array); // move the internal pointer to the end of the array
$last_key = key($halls_all_array);// fetches the key of the element pointed to by the internal pointer
try this code:
<?php
/*get the last key*/
end($halls_all_array);
$last_key = key($halls_all_array);
foreach($halls_all_array as $key => $row){?>
<td nowrap class="auto-style34" style="height: 30px; width: 20%" align="left">
time1-<?php echo format_time($row[$start]['time'])?>
</td>
<?php if ($last_key == $key): ?>
<td><?php echo $row ?></td>
<?php endif ?>
<?php } ?>
Please write code like this:
<?php
$counter = 0; // start a counter
$total_count = count($halls_all_array); //total Counts
foreach($halls_all_array AS $row){?>
<td nowrap class="auto-style34" style="height: 30px; width: 20%" align="left">
time1-<?php echo format_time($row[$start]['time'])?>
<?php if($total_count==$counter) echo 'word'; ?> // you condition for last and word
</td>
<?php
$counter++;
}
?>

PHP foreach loop is taking time to load thousands of table data in Google Chrome

On a page I have 8500 Employees shown in table data in the form of <tr> and <td>.
The Name of the Employees shown with a checkbox in front of each name of employee.
When I click on checkboxes the I insert the employees data (Employee Name and Employee Id) session.
Everything is working fine but the problem is when I click on check All checkbox then all the employees checkboxes are selected then there is a button named as "View Selected". On the click of this button I want to all the selected employees. When user click on this button a new child window will be opened with selected employee data in the form table row and data.
I am doing this but using session which I have created on the click of employees checkboxes.
Everything is working on Mozilla Firefox but when I check this of Google Chrome then it is not working and I am getting the browser message KillPages or Wait. The loader image of Chrome is shown but data is not loading.
My new child window page code is this where I am reading the session and running the for-each loop to print the data in the form of table data.
<?php require_once("../../includes/global.php");
$sessionName = rq('sessionName');
$employees = $session->read($sessionName);
?>
<script type="text/javascript" src="<?php echo SITEURL_PAGE; ?
>configuration/js/attendancePolicy.js"></script>
<div style="width: 100%;">
<?php if(strpos($sessionName, 'location') !== false) {?>
<h3 style="padding-left:10px;">View <?php echo LOCATION_DISPLAY_NAME?>s</h3>
<?php } else {?>
<h3 style="padding-left:10px;">View <?php echo
us(substr(str_replace('ot_','',$sessionName), 0, -3))?></h3>
<?php }?>
<?php
$totalEmployees = $session->check($sessionName) ? (int)count($session->read($sessionName)) : 0;
?>
<form id="updateEmployeesForm" name="updateEmployeesForm" method="post" action="saveAttendancePolicy.php">
<input type="hidden" name="hidAction" value="addNewPolicy_step3" />
<input type="hidden" name="sessionName" id="sessionName" value="<?php echo $sessionName?>" />
<?php
$styleTab = '';
$style='';
if($totalEmployees > 30){
$styleTab = 'border-bottom: none;';
$style = 'overflow:auto; height: 230px !important; border-bottom: 4px solid #2C90D3;';
}
//for over time policy only
$functionSuffix = '';
if($sessionName == 'ot_locations_cb' || $sessionName == 'ot_divisions_cb' || $sessionName == 'ot_departments_cb' || $sessionName == 'ot_employees_cb') {
$functionSuffix = 'overTimePolicy';
}
$where = rq('where');
$employeeLoadPage = ($sessionName == 'ot_employees_cb')?'otpolicy_ajax':'';
if(stripos($sessionName, 'employee') > -1) {
$js = "closeClildWindow('', 'employeeDiv', 'yes','".$employeeLoadPage."');";
} else if(stripos($sessionName, 'location') > -1) {
$js = "searchPolicySpecificNew('', 'locations', 'locationDiv', {'session':'yes'},'".$functionSuffix."'); updateChildPolicyNew('".$sessionName."', 'yes','".$functionSuffix."');";
} else if(stripos($sessionName, 'division') > -1) {
$js = "searchPolicySpecificNew('', 'divisions', 'divisionDiv', {'session':'yes'},'".$functionSuffix."'); updateChildDepartmentPolicyNew('".$sessionName."', 'locations_cb', 'yes','".$functionSuffix."');";
} else if(stripos($sessionName, 'department') > -1) {
$js = "searchPolicySpecificNew('', 'departments', 'departmentDiv', {'session':'yes'},'".$functionSuffix."'); updateChildjobTitlePolicy('".$sessionName."', 'divisions_cb', 'locations_cb', '','".$functionSuffix."');";
}
if($where == 'viewEmp') {
if($sessionName == 'ot_employees_cb') {
$js="getSelectedEmployeesNew('OT');";
} else {
$js="getSelectedEmployeesNew();";
}
}
?>
<div class="totalRecord" style="float:right; width:99%;text-align:right; margin-top: 5px;">
<label>Total Record(s) :<?php echo $totalEmployees ?></label>
</div>
<div style="margin: 0 2% 0 2%; width: 96%;" class="div_row">
<table cellpadding="0" border="0" cellspacing="0" width="100%" class="bdrtable" style="border-bottom: 0px;">
<thead>
<tr>
<th align="left" scope="col" colspan="5"> <input type="checkbox" name="viewCheckAllName" id="viewCheckAllName" <?php if($totalEmployees > 0) {?> checked="checked"<?php }?> class="class_parent_pop" onClick="sessionCheckBox('class_parent_pop', '<?php echo $sessionName?>_pop', 'parent', this);" />
Check All </th>
</tr>
</thead>
</table>
</div>
<div style="margin-bottom: 2%; margin-left: 2%; margin-right: 2%; width:96%;<?php echo $style;?>" class="div_row">
<table cellpadding="0" border="0" cellspacing="0" width="100%" class="bdrtable" style="<?php echo $styleTab?>">
<?php if($totalEmployees > 0) { ?>
<tr>
<?php $i=1;
foreach($employees as $key=>$employeeArr) {
?>
<td align="left" width="33%"><?php echo $i; ?> </td>
<?php
if($i%3 == 0 && $i != $totalEmployees) {
echo '</tr><tr>';
}
$i++;
}
if($totalEmployees%3 != 0) {
for ($x=($totalEmployees%3); $x < 3; $x++) {
echo '<td align="left" width="33%"> </td>';
}
}
?>
</tr>
<?php }else{ ?>
<tr>
<td colspan="3" align="center"><?php echo "No Data Found"; ?></td>
</tr>
<?php }?>
</table>
</div>
<div class="clear"></div>
<div class="div_row" style="text-align: right; width: 96%; margin:0 2%;">
<?php if($totalEmployees > 0) {?>
<input type="button" name="updateEmp" id="updateEmp" value="Update" class="submit" onClick="sessionCheckBoxPopupUpdate('<?php echo $sessionName?>_pop', '<?php echo $sessionName?>');<?php echo $js; ?>" />
<?php } ?>
<input type="button" name="cancel" id="cancel" value="Cancel" class="submit" onClick="javascript:window.close();" />
</div>
</form>
It may not be the foreach loop that is slow, 8500 is good number of data to load, you might want to page the results.
Why don't you try the same query using phpmyadmin and see the time taken.

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 } ?>

How to Display every 3 results in a row using mysql?

By using the below code i displayed 9 images, but all images are align side by side, how to display the every 3 images in one row and another3 images in another row ?
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<?php $sel = $db->query("select * from gallery order by gallery_cat_id asc limit 1,1");
while($row=mysql_fetch_array($sel)){ ?>
<tr><td align="left" valign="top"><table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody><?php $sel1 = $db->query("SELECT DISTINCT ( i.gallery_album_id )
FROM mov_gallery_album AS a, mov_gallery_images AS i
WHERE a.gallery_album_id = i.gallery_album_id
AND a.gallery_cat_id =".$row['gallery_cat_id']."
ORDER BY a.gallery_album_id DESC
LIMIT 0 , 9 "); if(mysql_num_rows($sel1)>0){ ?>
</tr><tr>
<?php
while($row1=mysql_fetch_array($sel1)){
$dis1 = $db->getRow("select * from ".ALBUMS." where gallery_album_id=".$row1['gallery_album_id']." limit 0,1");
$dis2 = $db->getRow("select * from ".GALLERY." where gallery_id=".$dis1['gallery_id']." limit 0,1");
$dis3 = $db->getRow("select * from ".ALBUMSIMAGES." where gallery_album_id=".$row1['gallery_album_id']." limit 0,1");
$dis4 = $db->getRow("select * from ".GALLERYCATEGORY." where gallery_cat_id=".$dis2['gallery_cat_id']." limit 0,1");
?>
<td align="left" width="100%"><table border="0" cellpadding="5" cellspacing="0">
<tbody><tr><td align="center" height="8" valign="middle" width="80">
<div style="border:0px;clear:both;padding-bottom:100px;margin-left:-110px;">
<div class="image_stack1"><a href="<?php echo SITE; ?>album/<?php echo ucfirst($dis1['gallery_cat_id']); ?>/<?php echo ucfirst($dis1['gallery_id']); ?>/<?php echo ucfirst($row1['gallery_album_id']); ?>/">
<img id="photo3" src="<?php echo SITE; ?>uploads/gallery/<?php echo $dis4['folder']; ? >/<?php echo $dis2['folder']; ?>/<?php echo $dis1['folder']; ?>/thumb/<?php echo $dis3['image']; ?>"width="80" height="80">
<div class="namehover1"><?php echo substr(ucfirst($dis1['name']),0,13); ?></div>
</a></div></div></td></tr></tbody></table></td><?php } ?></tr><tr><td class="midtitle" align="center" valign="middle"> </td></tr>
<tr><td style="padding-right: 10px;" align="right" colspan="4"><a href="<?php echo SITE; ?>gallery/<?php echo ucfirst($row['gallery_cat_id']); ?>/" class="midtitle">
<img src="http://www.img./viewall.png" border="0"/>
</a></td></tr><?php } ?></tbody></table></td></tr><?php } ?></tbody></table>
It would be wise to use div rather than table.
Some lines of css would do the trick. You wont have to logically determined to move to next line after 3 images. Here's how you can do with this in css
Lets have a div container for the all the images.
<style>
#photo_wrapper {
width:600px;
}
.photo {
width:150px;
height:150px;
display:block;
float:left;
border:6px #c5d0d6 solid;
margin-right:5px;
margin-bottom:5px;
overflow:hidden;
}
</style>
<div id="photo_wrapper">
<img src="image.jpg" class="photo"/>
<img src="image.jpg" class="photo"/>
<img src="image.jpg" class="photo"/>
<img src="image.jpg" class="photo"/>
<img src="image.jpg" class="photo"/>
<img src="image.jpg" class="photo"/>
</div>
this is generally done with the modulo (remainder after division) operator:
foreach ($results as $nr => $row) {
if (($nr % 3) == 0) echo '<tr>';
...
if (($nr % 3) == 0) echo '</tr>';
}
The concept is simple, use a counter and each time this counter MOD 3 is zero , start a new line.Or just count until 3 and reset the counter.
$i = 1;
while( $data = ....)
{
if($i == 1)
{
echo "<tr>"; //new line
}
echo "<td> .... </td>";
if($i == 3)
{
$i = 1;
echo "</tr>";
}
else
{
$i++;
}
}
//IMPORTANT! PLEASE NOTICE TO THIS PART: (OUT OF THE LOOP)
if($i < 3)
echo "</tr>";
you can put 9 photos in a div, then fix the width of that div to make it enough for only 3 photos in a line. And set float:left; for img tag in CSS.

Categories