3x3 table with random images - PHP - 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.

Related

Displaying an image in php

how to display blank if there is no image in a record.As i have inserted a record in database without an image but while fetching an record it is displaying an blank image in front end.It should not show any image if there is no image.Here is my code. If there is no image it should show only description.
Blogimage.php
<tbody>
<?php include "blogs.php" ;
while($row = mysql_fetch_array($result))
{?>
<tr>
<td><img src="admin/upload/<?php echo $row['image'];?>" height="100" style="width:60%;height:50%;"/></td>
</tr>
<tr>
<td><?php echo "<p style='width:60%;'>" .$row['blog_description']."</p>"; ?></td>
</tr>
<?php }?>
</tbody>
Blogs.php
$id=$_GET['title'];
$res = "SELECT * FROM blogs
WHERE blog_title='$id'";
$result=mysql_query($res);
try changing this
<img src="admin/upload/<?php echo $row['image'];?>" height="100" style="width:60%;height:50%;"/>
to this
<?php if($row['image']) echo "<img src='admin/upload/".$row['image']."' height='100' style='width:60%;height:50%;' />"; ?>
A couple of general points before we go into this
1) The MySql library you are using is old and busted - you should be using something newer - read this - the options are Mysql PDO and MySqli - I promise you, you will be glad you did, i use IDIORM as an interface and find it very good (Also helps prevent stuff in point 2 below!)
2) Your code can be SQL injected - more about that here - this is very bad :)
Below is an example, I have fixed the SQL injection problem, and put in some logic that would test to see if there is an image, if not, it will dump out a 'noimage.jpg' src value.
I have removed the include, and just simply put the code for blogs.php inline.
<tbody>
<?php
//START CODE FOR BLOGS.PHP
$query = sprintf("SELECT * FROM blogs WHERE blog_title='%s'",
mysql_real_escape_string($_GET['title']));
$result = mysql_query($query);
//END CODE FOR BLOGS.PHP
while($row = mysql_fetch_array($result))
{
if(!empty($row['image']) && strlen($row['image']) > 4)
{
$iamgeSrc = 'admin/upload/' . $row['image'];
}
else
{
$imageSrc = 'admin/upload/noimage.jpg';
}
?>
<tr>
<td>
<img src="<?php echo $imageSrc; ?>" height="100" style="width:60%;height:50%;"/>
</td>
</tr>
<tr>
<td>
<?php echo "<p style='width:60%;'>" .$row['blog_description']."</p>"; ?>
</td>
</tr>
<?php
}
?>
</tbody>
If you want no image to show at all, then this would work
<tbody>
<?php
//START CODE FOR BLOGS.PHP
$query = sprintf("SELECT * FROM blogs WHERE blog_title='%s'",
mysql_real_escape_string($_GET['title']));
$result = mysql_query($query);
//END CODE FOR BLOGS.PHP
while($row = mysql_fetch_array($result))
{
$image = '';
if(!empty($row['image']) && strlen($row['image']) > 4)
{
$image = '<img src="admin/upload/'.$row['image'].'" height="100" style="width:60%;height:50%;"/>';
}
?>
<tr>
<td>
<?php echo $image; ?>
</td>
</tr>
<tr>
<td>
<?php echo "<p style='width:60%;'>" .$row['blog_description']."</p>"; ?>
</td>
</tr>
<?php
}
?>
</tbody>

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>

How can i sum dynamic array

My code is below
<?php
foreach($query2->result() as $row2)
{
$sub_head_id = $row2->sub_head_id;
?>
<tr>
<?php
$query3 = $this->db->select('farm_id')->get('spf_farm_info'); $she_am_total = 0;
foreach($query3->result() as $row3)
{
$farm_id_inner = $row3->farm_id;
?>
<td>
<?php
$s_h_e_amount = $this->report_model->get_amount($farm_id_inner,$head_id,$sub_head_id);
?>
</td>
<?php
}
?>
<td>
<?php
$total += $s_h_e_amount;
?>
</td>
</tr>
<?php
}
}
?>
Basically i want to know how can i solve it,
<tr>
<?php
$query3 = $this->db->select('farm_id')->get('spf_farm_info'); $she_am_total = 0;
foreach($query3->result() as $row3)
{
?>
<td>
<?php
echo "Total :";
echo $total;
?>
</td>
<?php
}
?>
<td>
Grand Total:
</td>
</tr>
Here, Table column will increase dynamically, and will get different value every td(may be 2/3/4/..) from get_amount function.
Now i want to sum every tr's value according to column.
here it will be sum dynamically which will be show.
Please help me how can i solve properly
Simple SOlution is Take Four Variables
$Cola_total=0;
$Colb_total=0;
$Colc_total=0;
$Cold_total=0;
in your loop sum these Columns
foreach($array as $val){
echo "<tr><td>$val[0]</td> <td>$val[1]</td> <td>$val[2]</td><td>$val[3]</td></tr>";
$Cola_total=+$val[0];
$Colb_total=+$val[1];
$Colc_total=+$val[2];
$Cold_total=+$val[3];
}
and after the loop put the sum in last row
echo "<tr><td>$Cola_total</td> <td>$Colb_total</td> <td>$Colc_total</td><td>$Cold_total</td></tr>";
it may give you some idea
Here , since using Codeigniter, it will be used that select_sum(). then will get proper result.

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.

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.

Categories