PDO echo data in table rows and cells - php

I'm trying to echo out data from my database using PDO and have it create a table with 4 columns and as many rows until there is no more data to echo out. Right now there should be 16 items in the database, so I should have 4 rows, but I can't get my data to echo in that format, 4 columns and 4 rows. It just echoes out in one rows and 16 columns. Thanks in advance for the help.
Here is the php code I have so far:
echo "<table>";
for($x = 0;$x<1;$x++){
foreach($result as $row){
echo "<td>{$row['question_name']}</td>";
}
echo "</tr>";
}
echo "</table>";

HTML tables are really bad for this. Instead, try using a plain list and use CSS to turn it into a grid
?>
<ul class="grid">
<?php foreach ($result as $row) : ?>
<li><?= htmlspecialchars($row['question_name']) ?></li>
<?php endforeach ?>
</ul>
and some CSS
.grid {
list-style: none;
width: 512px;
}
.grid li {
float: left;
width: 128px;
height: 128px;
}
If you really want to persist with the table approach, you need to detect every fourth entry and close / re-open a table-row, eg
?>
<table class="grid">
<tr>
<?php foreach ($result as $i => $row) : ?>
<td><?= htmlspecialchars($row['question_name']) ?></td>
<?php if (($i + 1) % 4 == 0) : ?></tr><tr><?php endif ?>
<?php endforeach ?>
</tr>
</table>

Related

PHP - create dynamic html table with spacer columns

I am trying to create a dynamic grid (HTML table) using php.
I need to make a table with 5 columns per row and all the odd columns will have a width of 32% whereas the even columns will be empty but have a width of 2% which is used as spacers.
I also need it so if any row doesn't have 3 odd columns, it must generate the rest to make 5 even if they are empty.
I've managed to do it so it creates 3 columns of 32% width and adds empty TDs if it needs to be I haven't been able to create the smaller 2% columns.
This is going to be used as a table grid for an HTML email
This is what I have working at the minute but only 3 columns
<?php
$test = array(1,2,3,4,5);
$count = 0;
?>
<html>
<head>
<style>
.test {border: 1px solid #ccc;}
</style>
</head>
<body>
<table cellspacing="0" cellpadding="0" border="0" width="650">
<?php foreach($test as $t): ?>
<?php if ($count % 3 == 0) echo "<tr>"; # new row ?>
<td width="32%" class="test">
<p>ddfhfdhfgh</p>
<p>sdgdfgdgd</p>
</td>
<?php $count++; ?>
<?php if ($count % 3 == 0) echo "</tr>\n"; # end row ?>
<?php endforeach; ?>
<?php if ($count % 3 != 0): ?>
<?php while ($count++ % 3): ?>
<td width="32%"> </td>
<?php endwhile; ?>
</tr>
<?php endif; ?>
</table>
</body>
</html>
and I've tried adding this but it makes a mess.
<?php if ($count % 3 == 0) echo "<tr>"; # new row ?>
<?php if ( $count & 1 ): ?>
<td width="32%" class="test">
<p>ddfhfdhfgh</p>
<p>sdgdfgdgd</p>
</td>
<?php else: ?>
<td width="2%"> </td>
<?php endif; ?>
<?php $count++; ?>
All i need is a table with 3 large columns and 2 spacer columns in between
I think this should do the trick.
You were making it a bit more complex than it needs to be.
First you can make use of the foreach syntax like this foreach ($array as $index => $value) so you dont need to keep your own counter.
Second, you basically want every other column to take a different size so use % 2 and not % 3 and a simple if then else construct.
It also makes code easier to read if you dont use the php start and stop tags <?php ... ?> around every line of PHP, if you have more than one line of consecutive php code just use one to start the interpreter above the first line and one after the last line of PHP code. Otherwise it tends to Fry the brain trying to read and understand the code.
<?php
$test = array(1,2,3,4,5);
?>
<html>
<head>
<style>
.test {border: 1px solid #ccc;}
</style>
</head>
<body>
<table cellspacing="0" cellpadding="0" border="0" width="650">
<?php
echo '<tr>';
foreach($test as $i => $t):
if ( $i % 2 == 0 ) :
echo '<td width="32%" class="test">';
echo '<p>ddfhfdhfgh</p>';
echo '<p>sdgdfgdgd</p>';
echo '</td>';
else :
echo '<td width="2%" class="test"> </td>';
endif;
endforeach;
// if array has less than the expected 5 occ add blank columns
if ( $i < 5 ) :
$i++;
for ( $i ; $i < 5; $i++ ) :
if ( $i % 2 == 0 ) :
echo '<td width="32%" class="test">Filler</td>';
else :
echo '<td width="2%" class="test"> </td>';
endif;
endfor;
endif;
echo '</tr>';
?>
</table>
</body>
</html>

display series of products from mysql table

i am working on one project, where i need to display products from mysql table using php.
My design is like that, 5 products display in one row and so on.
So if there is 7 products in table, it should be 2 rows.
first row 5 products
second row 2 products
I am using <UL> and <LI> to display product and row like
<UL>
<li>first</li>
<li>2nd</li>
<li>3rd</li>
<li>4th</li>
<li>5th</li>
</ul>
<UL>
<li>6th</li>
<li>7th</li>
</ul>
I am wondering how to use foreach loop to get code like above.
If i use forloop with 5 increment i am unable to get products from table and display their name.
Thanks
echo '<ul>';
foreach ($yourResultSet as $index=>$data) {
echo '<li>' . YourOutput . '</li>';
if ($index % 5 == 0) {
echo "</ul><ul>";
}
}
echo '</ul>';
<ul>
<?php $i = 0; ?>
<?php while($row = mysql_fetch_array($result)): /* Used to loop through a resultset*/ ?>
echo "<li>".$row['data'].</li>";
<?php
$i++; // Increment by one every loop
if($i == 5){ // We've hit the fifth iteration
echo '</ul><ul>'; // Close the UL and open a new UL
$i = 0; // Set $i back to 0 and continue looping
}
endwhile;
?>
</ul>
Try that.
your best way of achieving this is to have your <li>'s have a specific width so that five of them fit in the parent container and that the following two or however many you have will drop to the next line.
<style>
#container {
width: 350px;
background: red;
padding:0;
margin: 0;
}
#list li
{
display: inline-block;
width: 50px;
height: 50px;
list-style-type: none;
background:blue;
margin: 2px;
padding: 0;
}
</style>
<div id="container">
<ul id="list">
<?php
while($row = mysql_fetch_array($result))
{
echo '<li>' . $row['data'] . '</li>';
}
?>
</ul>
</div>
You'll need to play with the sizes a bit but everything should work, and it you have 11 products this should do 2 rows of 5 and a third row of 1 product.

keeping track of pages and mysql_num_rows

Working off my previous question I'm trying to figure out how to achieve what I'm after.
I have an order that gets made. When the time comes to print that order, if the order has more than 25 lines/rows i need to put up from line 26 and create a new page. My question is how would I write that? I was thinking with mysql_num_rows but how can I track that?
How would I break it down, say put rows 0-24 into array1 then put rows 25-49 into array2 and so on? Then put the different arrays into while loops?
Maybe put everything into an array, then split it up?
Here's what I have right now
<?php
if (isset($_POST['CheckBox'])){
$CB = $_POST['CheckBox'];
} else {echo 'Nothing Marked'; die;}
/////////////////////////////////////////
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
#media print{ #page{margin: 5%;} }
body{
background-color: #CCC;
margin:0;
padding:0;
}
#MainWrapper{
margin:0 auto;
width:675px;
height:900px;
background-color:#3CF;
position:relative;
}
#OrderInfo{
width:200px;
height:50px;
background-color:#6C6;
float:left;
font-family:Verdana, Geneva, sans-serif;
font-size:9px;
}
#OrderInfoNotes{
width:475px;
height:50px;
background-color:#6C6;
float:right;
font-family:Verdana, Geneva, sans-serif;
font-size:9px;
}
#LineHeader{
width:675px;
background-color:#C90;
float:left;
}
.OrderLines{
font-family:Verdana, Geneva, sans-serif;
font-size:9px;
padding:0px;
}
.PBA{page-break-after: auto;}
.bigbold{ font-weight:bold; font-size:14px;}
.bigger{font-size:14px;}
</style>
</head>
<body>
<?php
///////////////////////////////////////////
foreach ( $CB as $thekey => $Order_ID )
{
$queryOrderHead = "SELECT * FROM Orders WHERE Order_ID = ".mysql_real_escape_string($Order_ID)."";
$queryOrderLines = "SELECT * FROM Order_LineDetails WHERE Order_LineDetails.Order_ID = ".mysql_real_escape_string($Order_ID)."";
//////////////////////////////////////////
if ($queryRunHead = mysql_query($queryOrderHead)){
//////////////////////////////////////////
// THIS IS THE HEADER OF THE ORDER ///////
//////////////////////////////////////////
while ($info_HEAD = mysql_fetch_array($queryRunHead))
{
$OrderDate_HEAD = $info_HEAD['OrderDate'];
$shippingservice_HEAD = $info_HEAD['shippingservice'];
$OrderNotes_HEAD = $info_HEAD['OrderNotes'];
?>
<div id="MainWrapper">
<!--START ORDERINFO INTO -->
<div id="OrderInfo">
Order ID:<span class="bigbold"><?php echo ' '.$Order_ID; ?></span><br>
<?php echo 'SHIPPER: <span class="bigbold">'.$shippingservice_HEAD.'</span>'; ?><br>
<?php echo 'ORDER DATE: '.$OrderDate_HEAD; ?>
</div>
<div id="OrderInfoNotes">
<?php echo 'NOTES: '.$OrderNotes_HEAD; ?></div>
<!--END ORDERINFO INTO -->
<hr><br>
<div id="LineHeader">
<table class="OrderLines">
<tr class="bigbold">
<td width="300"><u>Product Name:</u></td>
<td width="90"><u>UPC Code:</u></td>
<td width="50" align="right"><u>PID:</u></td>
<td width="75" align="right"><u>QTY:</u></td>
<td width="160" align="right"><u>Packer:</u></td>
</tr>
<?php
}
/////////////////////////////////////////
// THIS IS THE ORDER LINES //////////////
/////////////////////////////////////////
$queryRunLines = mysql_query($queryOrderLines);
while ($info = mysql_fetch_array($queryRunLines))
{
$ProductName_LINE = $info['ProductName'];
$qty_LINE = $info['qty'];
$Product_ID_LINE = $info['Product_ID'];
$UPC_LINE = $info['UPC'];
?>
<tr class="bigger">
<td><?php echo $ProductName_LINE; ?></td>
<td><?php echo $UPC_LINE; ?></td>
<td align="right"><?php echo $Product_ID_LINE; ?></td>
<td align="right"><?php echo $qty_LINE; ?></td>
<td></td>
</tr><tr>
<td colspan="5"><hr></td></tr>
<?php
}
///////////////////////////////////////////////////////////
// END OF ORDER LINES /////////////////////////////////////
///////////////////////////////////////////////////////////
$numRows = 0;
$numRows = mysql_num_rows($queryRunLines);
echo 'Total Rows ('.$numRows.')'
///////////////////////////////////////////////////////////
?><tr>
<td colspan="5" class="center">--- :END: ---</td>
</tr>
</table>
</div>
</div>
<p class="PBA"/>
<?php
} else {
echo mysql_error();
}
}
mysql_close($conn);
?>
</body>
</html>
From looking at your previous question, it appears you want to print the HTML page, not use pagination. Just use a counter variable:
$i = 0;
while ($info = mysql_fetch_array($queryRunLines))
{
$ProductName_LINE = $info['ProductName'];
$qty_LINE = $info['qty'];
$Product_ID_LINE = $info['Product_ID'];
$UPC_LINE = $info['UPC'];
if (!($i % 25)) {
// echo page break every 25 lines
}
// output
$i++;
}
Also take a look at CSS attributes page-break-before/page-break-after. I would also suggest using an HTML to PDF converter. They are easy to use and will make your printed documents consistent across different systems.
What you need is called pagination.
One of the way to do it is, use LIMIT clause in your query.
I would have put up here but there are hundreds of tutorials for pagination in google with good explanation. It would be better if you search by "php pagination" and learn step by step.
you can limit the number of rows returned by your query,
add LIMIT 0, 24 at the end of your query, you will get the first 25 rows.
you can have more details here
Use a variable to store how many rows you want to display and another one to store the current rows being retrieved.
Look up pagination which will give you a better idea. It may not be exactly what you what but will teach you how to limit sql results they way you want.

displaying table with images with PHP

I need to generate a table with php, that will display the images - names stored on database. It has to display 3 images in a row. The images are added to the database all the time, so I need that to be automatically generated, instead of hard coding the tables. I am not sure how do I do that? Please help!
You need to cycle the result recordset and print out the new row every 3rd element.
For example:
<table>
<tr>
<?php $i=0; foreach ($images as $image): ?>
<td><?php echo $image['name'] ?> <img src="<?php echo $image['path'] ?>" /></td>
<?php if(++$i%3==0): ?>
</tr><tr>
<?php endif ?>
<?php endforeach ?>
</tr>
</table>
suppose u get the all images name from database in an array
$img_array = array(
1=>'f.jpg',
2=>'s.jpg',
3=>'t.jpg',
4=>'f.jpg',
5=>'e.jpg'
);
// now create dynamic table via php
<table border="1" cellpadding="2" cellspacing="2" width="100%">
<tr>
<?php
$i=0;
foreach($img_array as $k){
if($i%3==0) { ?> </tr><tr> <?php } ?>
<td><img src="<?php echo $k?>" border="0"></td>
<?php $i++; } ?>
</tr>
</table>
Note: please write full path of image in src before <?php echo $k?>
Iterate the image records, using modulo 3 to change to the next table row.
Something like:
echo '<table><tr>';
foreach ($images) {
echo '<td>$image</td>';
if ($i % 3 == 0) {
echo '</tr><tr>';
}
}
echo '</tr></table>';
A simple table like that would be like
<table>
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>1</td><td>2</td><td>3</td></tr>
</table>
To generate this automatically you need to store where you are in the table, first col, 2nd col or 3th col.
<?php
$pos = 1;
print "<table>"
for ($i=0; $i<=10;$i++)
{
if ($pos==1)
{
print "<tr><td>1</td>";
$pos=2;
}
else if ($pos==2)
{
print "<td>2</td>";
$pos=3;
}
else if ($pos==3)
{
print "<td>3</td></tr>";
$pos=1;
}
}
if ($pos==2 || $pos==3)
print "</tr>";
print "</table>"
Keep in mind that if you use the options with $i%3 from the other comments, that your table will start end/or finish with an empty row. This would need additional checks. The $i%3 will give the remainder of the division of $i and 3. So when $i/3 == 0, means it is true on every third row.

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

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>

Categories