displaying table with images with PHP - 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.

Related

3x3 table with random images - PHP

I'm new here and need some help. I'm doing a web development course and have an assignment I need a hand with.
Basically, I want to send a query that picks 9 random records, and show the result as a 3x3 table.
Here's my code so far:
<div id="productgrid">
<?php
$query = mysqli_query($conn, "SELECT * FROM products
ORDER BY RAND()
LIMIT 9");
?>
<h2>Featured Products</h2>
<table>
<?php
while($products = mysqli_fetch_array($query)){
$file = $products['prod_img'];
$pid = $products['prod_id'];
$product_price = $products['prod_price'];
$image_id = $products['prod_id'];
$desc = $products['prod_desc'];
?>
<tr>
<div class="bigred">
<td class="bigred">
<?php echo '<b>'. "$product_price".'</b>'; ?>
</td>
</div>
</tr>
<tr>
<td>
<img src="<?php echo $file ?>" height = "150px" width="150px"/><br />
</td>
<div class="smallblack"
</tr>
<tr>
<td class = "smallblack">
<?php echo '<b>' . "$desc".'</b>'; ?>
</td>
</tr>
</div>
<?php } ?>
I can get it to generate the 9 random images but it puts them all directly under each other in one long column. Is there a way I can get them to display in 3 rows of 3?
I apologise if this is a dumb question, but I'm only starting out and appreciate the help.
Thank you :)
Pic attached as sample
<?php
// A counter which is incremented by one for each product row
// in the loop below.
$i = 0;
echo "<table>\n";
echo "<tr>\n";
while ($product = mysqli_fetch_array($query)) {
// Re-open HTML row, if $i is divisible by 3
if ($i++ % 3 == 0) {
echo "</tr><tr>\n";
}
// Escape the `src` attribute value as appropriate, according to the
// logic of your app. This is just a sample.
$img_src = htmlspecialchars($product['prod_img']);
echo <<<HTML
<td>
<div><img src="{$img_src}"/></div>
<div>{$product['prod_desc']}</div>
<!-- Put the rest of the fields here -->
</td>
HTML;
}
// Add cells for the rest of the columns (if any)
while ($i++ % 3 != 0) {
echo "<td></td>\n";
}
echo "</tr>\n";
echo "</table>\n";
?>
P.S.: I recommend using a template engine such as Smarty, or Twig. With the help of a template engine you can make the markup much more readable and maintainable.
You should change your table out put and use 3 <td> tags instead of just the one, like so...
<table>
<tr>
<?php
$counter = 0; // Needs to be outside of the loop...
while($products = mysqli_fetch_array($query)){
$file = $products['prod_img'];
$pid = $products['prod_id'];
$product_price = $products['prod_price'];
$image_id = $products['prod_id'];
$desc = $products['prod_desc'];
?>
<td class="bigred">
<?php echo '<b>'. "$product_price".'</b>'; ?>
<img src="<?php echo $file ?>" height = "150px" width="150px"/><br />
<?php echo '<b>' . "$desc".'</b>'; ?>
</td>
<?php
// Check to see if you have looped through three times and close the <tr> tag.
if($counter % 3 === 0) {
echo '</tr><tr>';
}
$counter++
?>
</table>
If there is more than 9 images, then it will keep creating table rows and cells and you will need more logic to handle that, however, this should work for 9 images.
A more elegant way to handle this would be to use <div> tags and floats, but since you are already using a table, I formatted it as such.

unique id for dynamic table

I will be generating a HTML table with data pulled from MySQL.The number of rows in my MySQL table are not fixed.
<?php
while($row=mysql_fetch_assoc($result))
{ ?>
<tr>
<td><?php echo $row['col1'];?></td>
<td><?php echo $row['col2'];?></td>
</tr>
<?php } ?>
Now how do I have the table rows and table data elements assigned unique id ??
Another loop to generate them won't work as I can't set an exit condition for the new loop as number of rows are not fixed.
Please guide me as to how to go forward about it. I can only use Javascript and not JQUERY.
Why can't you do something like this ?
<?php
$i = 1;
while($row=mysql_fetch_assoc($result))
{ ?>
<tr id="row<?php echo $i;?>">
<td id="cell-left-<?php echo $i;?>"><?php echo $row['col1'];?></td>
<td id="cell-right-<?php echo $i;?>"><?php echo $row['col2'];?></td>
</tr>
<?php
$i++;
} ?>
Please note, I have added ids row, cell-left- and cell-right- by myself. You may change them as per your requirements.
You can use a counter when iterating through the rows, maybe something like this:
<?php
$rowCount = 0;
while($row=mysql_fetch_assoc($result))
{
$rowCount++;
?>
<tr id="<?php echo 'row' . $rowCount;?>">
<td><?php echo $row['col1'];?></td>
<td><?php echo $row['col2'];?></td>
</tr>
<?php
}
?>
You can now select an element with
var rowID = 1;
document.getElementById("row" + rowID);
Hope this helps.

Odd and Even Rows for a table

I have a table that get its rows from a MYSQL database
<table id="table1">
<?php
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_query("SET NAMES `utf8`"); // UTF 8 support!!
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
?>
<?php echo $row['Header'].""; ?>
<tr>
<td id='date'><?php echo $row['Date'].""; ?></td>
<td id='time'><?php echo $row['Time'].""; ?></td>
<td id='hometeam'><?php echo $row['HomeTeam'].""; ?></td>
<td id='score'><?php echo $row['Score'].""; ?></td>
<td id='awayteam'><?php echo $row['AwayTeam'].""; ?></td>
<td id='other'><?php echo $row['Other'].""; ?></td>
</tr>
<?php } mysql_close(); ?>
</table>
i have 2 css class called "A" and "B" for Odd Rows and Even Rows
i currently getting this done by replacing <tr> with <tr class='<?php echo $row['Row'].""; ?>'> and i have in my Database table a column "Row" which i add in A or B for even or odd row... the problem is if i wanna delete or add a new row between one of these i will have to change all the A and B in the other.
I have seen in another questions many way to do that in javascript or jquery but for a normal table with TR's which is not my case...(tried some of these scripts but couldn't get it fixed)
So what i want an easier way to do that Even and Odd rows, Thanks!
do it in CSS way (no inline class) once and for all:
in CSS:
#table1 tr:nth-child(odd) td { background-color:#ebebeb }
#table1 tr:nth-child(even) td { background-color:#0000ff }
in your HTML:
<table id="table1">
thats it, no matter if your table rows are removed/or not.
You can add those classes using jQuery easily like this
$(function(){
$('#table1 tr:odd').addClass('A');
// for even
$('#table1 tr:even').addClass('B');
});
Why didn't you use modulo in your while loop ? It's a better way than store your class in your database... :
$i = 0;
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
?>
<?php echo $row['Header'].""; ?>
<tr class="<?php echo $i%2 == 0 ? "class_A" : "class_B" ; $i++;?>" >
<td id='date'><?php echo $row['Date'].""; ?></td>
<td id='time'><?php echo $row['Time'].""; ?></td>
<td id='hometeam'><?php echo $row['HomeTeam'].""; ?></td>
<td id='score'><?php echo $row['Score'].""; ?></td>
<td id='awayteam'><?php echo $row['AwayTeam'].""; ?></td>
<td id='other'><?php echo $row['Other'].""; ?></td>
</tr>
<?php } mysql_close(); ?>
<?php
$class="odd"
while($row = mysql_fetch_array($rs)) {
$class = ($class=='even' ? 'odd' : 'even');
?>
<tr class="<?php echo $class">
...
</tr>
<?php } ?>
There are many ways to do this, PHP, Javascript and even pure CSS. Here's the PHP way to add a class to every other row:
while($row = mysql_fetch_blahblah()) {
$i = 0; ?>
<tr class="<?php echo $i % 2 == 0 ? 'class1' : 'class2';?>">
<td>....</td>
</tr>
<?php
$i++; // increment our counter
}
Basically the modulus operator returns the remainder of dividing the nubmers either side of it, so for example 3 % 2 == 1, 4 % 2 == 0, 5 % 2 == 1, so we can tell if $i is odd or even and alternate the classes added to the <tr>.
IMHO you want to either do it this way for 100% guarantee it will work (no browser dependencies) or if you design your app for modern browsers go for the CSS route.

How to display two table columns per row in php loop

I would like to display data, two columns per row during my foreach. I would like my result to look like the following:
<table>
<tr><td>VALUE1</td><td>VALUE2</td></tr>
<tr><td>VALUE3</td><td>VALUE4</td></tr>
<tr><td>VALUE5</td><td>VALUE6</td></tr>
</table>
Any help would be greatly appreciated.
You can use array_chunk() to split an array of data into smaller arrays, in this case of length 2, for each row.
<table>
<?php foreach (array_chunk($values, 2) as $row) { ?>
<tr>
<?php foreach ($row as $value) { ?>
<td><?php echo htmlentities($value); ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
Note that if you have an odd number of values, this will leave a final row with only one cell. If you want to add an empty cell if necessary, you could check the length of $row within the outer foreach.
$i=0;
foreach ($x as $key=>$value)
{
if (fmod($i,2)) echo '<tr>';
echo '<td>',$value,'</td>';
if (fmod($i,2)) echo '</tr>';
$i++;
}
this will output TR (row) each second time
ps: i haven't tested the code, so maybe you will need to add ! sign before fmod, if it doesn't output TR on first iteration, but on second iteration in the beginning...
This would give you great table and for loop concept--
<table border="1" cellspacing="0" cellpadding="2">
<?php
for($x=1; $x<=20; $x++)
{
echo "<tr>";
for($y=1; $y<=20; $y++)
{
echo "<td>";
echo $x*$y;
echo "</td>";
}
echo "</tr>";
}
?>
</table>
<table>
<?php
$i=0;
foreach ($x as $key=>$value)
{
if (!$i%2) echo '<tr>';
echo '<td>',$value,'</td>';
if ($i%2) echo '</tr>';
$i++;
}
?>
</table>

Print database data in html Table

I know how to print data from database on html table but i have one task that i can not understand, and i can not do it.
I have a table in database and when i select those data i want them to display on html table but something like this:
Image http://img683.imageshack.us/img683/9350/tablea.png
To achieve a table layout like that you just need to condition the placement of the end of your table rows.
<table>
<tr>
<?php
$count = 0;
while($row = mysql_fetch_assoc($result)) :
$count++;
?>
<td><?php echo $row['value'] ?></td>
<?php if($count % 2 == 0 || $count == mysql_num_rows($res)) : ?>
</tr>
<?php if($count != mysql_num_rows($result)) : ?>
<tr>
<?php endif; ?>
<?php endif; ?>
<?php endwhile; ?>
</table>
What the above does is use the modulus operator (%, calculates the remainder from division) to print a closing and opening row tag whenever we're at an evenly numbered result.
Also, if you wanted to change your table layout to be 3 or 4 columns wide all you need to do is change the number applied to the modulus:
$count % 3 == 0 //3 columns
$count % 4 == 0 //4 columns, etc
<table>
<?php while (TRUE) { ?>
<?php
// Make an array of n rows. Trailing items may be FALSE if there
// are not enough rows to fill the table row.
//
$rows= array();
for ($i= 0; $i<n; $i++)
$rows[$i]= mysql_fetch_assoc($result);
if (!$row[0])
break;
?>
<tr>
<?php foreach ($rows as $row) { ?>
<td>
<?php if ($row) { ?>
Value: <?php echo(htmlspecialchars($row['value']); ?>
<?php } ?>
</td>
<?php } ?>
</tr>
<?php } ?>
</table>

Categories