How to put images on a 3 by 3 table? - php

I am using php/mysql, and have a database table with image url. I would like to know how can I put them on a php page with a 3 x 3 table, such that each td will show a different image based on the image url from the database?
I want to create something like this, where the alphabets are the images:
|a|b|c|
|d|e|f|
|g|h|i|
So far, I am only able to use do while to create something like this:
|a| | |
|b| | |
|c| | |
Thanks.

This would be the general approach:
$query = "SELECT url FROM images LIMIT 9";
$resource = mysql_query($query);
# Get the number of images
$count = mysql_num_rows($resource);
$i = 0;
$per_row = 3;
# Start outputting the table
echo '<table><tr>';
while($row = mysql_fetch_assoc($resource)) {
# The image cell
echo '<td><img src="'.$row['url'].'" /></td>';
# If three cells have been printed, and we're not at the last image
if(++$i % $per_row == 0 && $i > 0 && $i < $count) {
# Close the row
echo '</tr><tr>';
}
}
# If the last row isn't 'full', fill it with empty cells
for($x = 0; $x < $per_row - $i % $per_row; $x++) {
echo '<td></td>';
}
echo '</tr></table>';
That is, just loop the results normally but on every third item, echo a row change (</tr><tr>). Just make sure that you don't print extra row changes at the beginning or the end, hence the additional conditions.
The resulting table should be something like this (line breaks added):
<table>
<tr>
<td><img src="image.jpg1" /></td>
<td><img src="image.jpg2" /></td>
<td><img src="image.jpg3" /></td>
</tr>
<tr>
<td><img src="image.jpg4" /></td>
<td><img src="image.jpg5" /></td>
<td><img src="image.jpg6" /></td>
</tr>
<tr>
<td><img src="image.jpg7" /></td>
<td><img src="image.jpg8" /></td>
<td><img src="image.jpg9" /></td>
</tr>
</table>

Use a counter to keep track of how many images you've displayed already, and only emit </tr><tr> every 3 images. Hint: $count % 3

You don't really need to do this with tables (think about it, you're just trying to display something in a grid, you're not really trying to create a table of things).
With a little CSS you can do it like this (you can use the appropriate HTML5 elements if you use html5-shiv for MSIE):
<div class="figure">
<img src="mypic.jpg" alt="">
<div class="description">Description goes here</div>
</div>
and in CSS:
.figure {
float: left;
margin-right: 10px; /* for space between the columns */
padding: 5px;
border: 1px solid #000;
background-color: #fff;
color: #000;
}
.figure .description {
margin-top: 1em;
font-variant: italic;
}
If they are all the same size and you want to force them into a NxN grid, you can wrap them in a div (class="grid") do something like this (3x3 grid, 100px inner figure width (i.e. 90px image width)):
.grid {
padding-left: 10px; /* to mirror the right margin of the last .figure in the row */
width: 350px; /* 3*100px + 2*10px margin + 3*2*5px padding */
}
.figure img {
width: 90px;
}
This way you can simply output the images in sequence in a loop without having to worry about where to wrap the rows (the wrapping is handled by CSS; if you don't force the grid to have a maximum width, it will wrap at the right end of the browser window).

Related

Calculate total price inside php table

I'm trying to show total price in a table.
I have 2 arrays where one is the names of the cars and second is the prices of each one.
I've managed do display the prices and the names inside the table,
but the thing is that i have a "checkbox" thing that shows if car is sold or not...
I'm trying to make the total calculation that calculate the total price of all checked checkboxes.
That means - when checkbox is on, the variable of total price should add that car's price to it.
here is how it should looks like:
I must mention that I've just started to learn php at collage,
here's the array and the variable:
<?php
$cars = array ("ford","fiat","renault","mazda");
$prices = array(100,80,90,120);
$sold = '<input type="checkbox" name="sold">';
?>
I added up basic style for my table (in the same php file)
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: center;
padding: 8px;``
}
</style>
and the php code for the table:
<?php
$cars = array ("ford","fiat","renault","mazda");
$prices = array(100,80,90,120);
$sold = '<input type="checkbox" name="sold">';
?>
<h1>list of cars</h1>
<table>
<th>name</th>
<th>price</th>
<th>sold</th>
<?php
for($i=0;$i<count($cars);$i++){
echo
"<tr>
<td>$cars[$i]</td>.
<td>$prices[$i]$</td>.
<td>$sold</td>.
</tr>";
}
?>
</table>
How can I calculate the amount of all checked checkboxes prices?
imvain2’s answer would be your best choice as it does not require a client-server roundtrip.
However, if you would like to do this in php, you need to associate the checkbox with the car in some way.
One way would be to tweak your for loop like so
for($i = 0; $i < count($cars); $i++) {
echo (
"<tr>
<td>{$cars[$i]}</td>
<td>{$prices[$i]}$</td>
<td><input type=\"checkbox\" name=\"sold[]\" value=\"{$prices[$i]}\"></td>
</tr>"
);
}
So when the form containing the table is submitted to the server you can do the calculation like
$total = 0;
foreach ($_POST['sold'] as $value) {
$total += (int)$value;
}
I would modify the checkbox to include the price as a data-attribute and put it within the for loop not outside of it.
$sold = '<input type="checkbox" data-price="$prices[$i]" name="sold">';
then in javascript just loop through the checkboxes and an event listener that checks for checked.
function showTotal(els) {
total = 0;
els.forEach(function(el) {
if (el.checked) {
total += +el.getAttribute("data-price");
}
});
document.querySelector("#total").innerHTML = "$" + total.toFixed(2)
}
sold = document.querySelectorAll("[name='sold']");
sold.forEach(function(el) {
el.addEventListener("change", function(ev) {
showTotal(sold)
});
});
to show the total you will need a div to hold the total
<div id="total"></div>
**Note: please fix my english if needed.
please notice that the hole code is written in single php file.
after quit a bit of time, i was mange to fix my code.
first, as suggest here before, the JS code that was given was written in jquery, i haven't learned that part of js yet, therefor i wrote the code with the help of my friend in js using dom.
CSS:
<style>
body {
text-align:center;}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 50%;
margin-left: auto;
margin-right: auto;
margin-top:15%;
}
th{
}
td, th {
border: 1px solid #dddddd;
text-align: center;
padding: 8px;
}
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
</style>
JS: (the location of the script tag doesn't matter at this point, but iv'e located it at the top of the php file inside header content.
<script>
function calcTotal() {
let sum = 0;
for (let index = 0; index < 4; index++) {
let priceAsStr = document.getElementById("price" + index).innerHTML;
let price = parseInt(priceAsStr);
let soldOrNot = document.getElementById("soldOrNot" + index).checked;
if (soldOrNot == true)
{
sum = sum + price;
}
}
document.getElementById("sum").innerHTML ="$" + sum;
}
and finally, for the body:
<?php
$cars = array("Ford","Fiat","Renault","Mazda");
$prices = array(100,80,137,453);
?>
<table>
<tr>
<th>Cars</th>
<th>Price</th>
<th>Sold</th>
</tr>
<?php
$sum = 0;
for ($i=0; $i < 4; $i++) {
echo "<tr id='row$i'>
<td>{$cars[$i]}</td>
<td id='price{$i}'> {$prices[$i]}$</td>
<td><input type='checkbox' id='soldOrNot{$i}' name='sold{$i}' onClick='calcTotal()' value=''> </td>
</tr>";
}
?>
</table>
<h1>Total Price: <span id="sum">0</span></h1>

Page Break After Specific Number Of Rows

I am developing a voucher printing application that prints serial numbers and pins from a MySQL table and displays them in a page.
The php code displays two records per row..with being in a separate column i.e two columns displayed side by side
Due to the format of the page (two records per row)..i can not display each record in a seperate table. Rather all records are contained in a "general" table.
The voucher printing requires two rows to be displayed on each page.
I implemented a "page-break-after: always" style to each row not divisble by two, but page break is not showing. My code is shown below:
$aray=array();
while($row=mysqli_fetch_array($sql_res))
{
$aray[]=$row;
}
$nr_elm=count($aray);
$table='<table width=100%><tr>';
$nr_col=2;
if($nr_elm>0)
{
$p=1;//This is the row counter
for($i=0;$i<$nr_elm;$i++)
{
$table.='<td><div style="border: 2px dashed #000;" ><div id="image" style="float:left;">
'.$p.' <img src="crswb1.png" height=80 width=60 />
</div><div id="texts" style=" float: none;
margin-left:60px;">
<p> Amount:'.$aray[$i]['amount'].' </p><p> Pin:17263648409</p><p> Serial:5374748548
</div></div></td>';
$col_to_add=($i+1)%$nr_col;
if($col_to_add==0)
{
if($p % 2 == 0) {
$table.="<tr style='page-break-after:always'>";
}
$table.='</tr><tr>';
$p++;
}
}
}
$table.='</tr></table>';
$table=str_replace('<tr></tr>','',$table);
echo $table;
?>
I viewed the page source and the "page break" style is showing for the neccessary row, as seen below
<tr style='page-break-after:always'></tr><tr><td><div style="border: 2px dashed #000;" ><div id="image" style="float:left;">
3 <img src="crswb1.png" height=80 width=60 />
</div><div id="texts" style=" float: none;
How can i ensure that the page break is displayed so that i can print only two rows per page?..Thanks.
The format of the page does not prevent you to use one table for every two values. E.g. use the following HTML Code:
<table id="table1">
<tr>
<td>This is cell No. 1 in Table 1</td>
<td>This is cell No. 2 in Table 1</td>
</tr>
</table>
<table id="table1">
<tr>
<td>This is cell No. 1 in Table 2</td>
<td>This is cell No. 2 in Table 2</td>
</tr>
</table>
together with the following CSS Code:
#media print {
table {page-break-after: always;}
/* prevent blank page at end */
table:last-of-type {page-break-after: auto;}
}
/* If you want the fields on one line */
table, tr {
width: 100%;
/* If the fields still don't fit on one line
* make the font-size smaller */
font-size: 0.9em
}
it will print one table per page. Notice that even the last table will cause a page-break.
To see this work I prepared a codepen here. Open the codepen and try to print the page. You should see every table on it's own page.

Adding z-index to php while loop

I have a procedural while loop that echos out rows in my DB like:
echo '<tr align="left"> <td>'.$row['address'].','.$row['state'].'</td>'.
'<td><a href="'.$row['shopurl'].'">'.$row['datedesc'].'</td>'.
'</tr>';
And works great! The problem now is that I need to add a "SOLD OUT" png across the address & state, of only one (currently) of the rows. I have CSS:
#sold-out{
background-image: url("/graphics/png/soldout.png");
}
With the image as the back-ground.
How can I add a Z-Index to php inside a While loop?
Thanks in advance!
You do not add z-index to PHP, you add it to CSS. However, in this case, you can simply print out an absolutely positioned div with the image in the td that you want.
PHP
foreach ($rows as $row) {
echo '<tr align="left">
<td>';
//conditional to determine if row is sold out
if ($row['soldOut'] === 'yes') {
echo '<div class="sold-out"> </div>';
}
echo $row['address'].','.$row['state'].'</td>'.
'<td><a href="'.$row['shopurl'].'">'.$row['datedesc'].'</td>'.
'</tr>';
}
CSS
.sold-out {
position:absolute;
background-image: url("/graphics/png/soldout.png");
opacity: 0.8;
top: 0;
left: 0;
right: 0;
bottom: 0;

displaying fetched mysql data using an external css

How can I attach an external CSS file to display data fetched from a MySQL database? Can I display data using CSS instead of using tables. I want to completely avoid tables in diplaying the fetched data.
This is the code to fetch data from the MySQL database:
<?php
echo "Database Date: " .date("Y-m-d");
?>
Variables included in this data are: Assigned NCL Number, Hospital, Age, Sex, Primary cancer and the date of diagnosis and latest management on the patient.
<style type="text/css">
table.data { width:100%; margin: 0;
border: 1px solid black; border-spacing: 2px; }
.id {width: 7%; background-color: #c7c7c0; }
.date {width: 12%; background-color: #d8d8d1; }
.nclnumber { width: 10%; background-color: #c7c7c0; }
.hospital {width: 17%; background-color: #d8d8d1; }
.age { width: 3%; background-color: #c7c7c0; }
.sex { width: 2%; background-color: #d8d8d1; }
.cancer { width: 10%; background-color: #d8d8d1; }
.dateofdiagnosis { width: 7%; background-color: #d8d8d1; }
.notes { width: 32%; background-color: #d8d8d1; }
</style>
<table class="data" border="0" cellspacing="2">
<tr>
<td class="id"><b>Id</b></td>
<td class="date"><b>Date</b></td>
<td class="nclnumber"><b>NCL Number</b></td>
<td class="hospital"><b>Hospital</b></td>
<td class="age"><b>Age</b></td>
<td class="sex"><b>Sex</b></td>
<td class="cancer"><b>Diagnosed Cancer</b></td>
<td class="dateofdiagnosis"><b>Date of Diagnosis</b></td>
<td class="notes"><b>Notes</b></td>
</tr>
</table>
<?php
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("cancer") or die(mysql_error());
$data = mysql_query("SELECT * FROM cancer WHERE Age ='1'OR Age = '2' OR Age = '3'OR Age = '4'OR Age = '5'OR Age = '6'OR Age = '7'OR Age = '8'OR Age = '9'")
or die(mysql_error());
while($info = mysql_fetch_array( $data )) {
echo "<table class='data' border='0' cellspacing='2'>
<tr>
<td class='id'>".$info['Id']."</td>
<td class='date'>".$info['Date']."</td>
<td class='nclnumber'>".$info['NCL_Number']."</td>
<td class='hospital'>".$info['Hospital']."</td>
<td class='age'>".$info['Age']."</td>
<td class='sex'>".$info['Sex']."</td>
<td class='cancer'>".$info['Diagnosed_Cancer']."</td>
<td class='dateofdiagnosis'>".$info['Date_of_Diagnosis']."</td>
<td class='notes'>".$info['Notes']."</td>
</tr>
</table>";
}
?>
There is absolutely no reason not to use <table> elements for tabular data.
The anti-table hysteria that some people have is simply a misunderstanding: it's bad to misuse tables for layouting purposes. There's nothing wrong with the HTML tag, though. In fact, using any other HTML element to display tabular data is bad for semantics.
The <table> tag and its contained <tr> rows and <td> columns informs the browser rendering it that the data therein is related and columnar. Don't think of the <table> (or any HTML tag for that matter) as strictly a visual display element. They convey meaning about the data to the machine which is parsing it.
Let's sort out a little confusion. Displaying in CSS instead of tables doesn't make since as tables and its associated tags are HTML elements and CSS is styling you can apply to those elements. They are not equivalent.
The alternative to tables would be to create a complex, complicated and convoluted layout using a combinations of divs and spans.
However, there is absolutely no reason why, if the data is tabular, that you should bother with such an awkward design just to avoid the use of the <table> tag. That's why the <table> tag is in the HTML spec.
Abusing the <table> tag for layout purposes has given the tag a bad rep. When used properly though (i.e. to display tabular data) it can be very very useful.
Best advice: use the <table> tag and follow the advice of the community wiki.

How to make a number list in a Table

I have a leaderboard on my website, and I want to be able to have rank numbers (1, 2, 3, 4, 5, etc) as using...
<ol>
<li>this</li>
<li>that</li>
</ol>
...doesn't work in a table
How can I do this?
One way of achieving this, given the following structure:
<table>
<thead>
<tr>
<th>Rank:</th>
<th>Name:</th>
</tr>
</thead>
<tbody>
<tr>
<td class="rank"><span></span></td>
<td>Him</td>
</tr>
<tr>
<td class="rank"><span></span></td>
<td>Her</td>
</tr>
</tbody>
</table>
Is to use CSS-counters:
table {
border: 1px solid #ccc;
empty-cells: show;
width: 40%;
counter-reset: ranking;
}
th {
border-bottom: 2px solid #ccc;
min-width: 4em;
width: 50%;
max-width: 6em;
}
tbody tr {
counter-increment: ranking;
}
td {
border-bottom: 1px solid #ccc;
}
td.rank > span:before {
content: counter(ranking);
}
And a JS Fiddle demo.
As noted elsewhere, though, these are not widely supported. And would be better-implemented either using JS/jQuery or by simply using an ol.
You could do this using CSS counters
...unfortunately they're not that widely supported yet. It's best to generate the numbers on the server side, it could be argued that they are significant content and should be in HTML anyways.
Simply add this to your CSS:
ol {
list-style-type: decimal;
margin-left:12px;
}
JSFiddle:
http://jsfiddle.net/Mutant_Tractor/zhCzQ/2/
Or you could also use list-style-type: decimal-leading-zero;
I'm afraid numbering rows in a table is a standard html feature. You'll need to resort to Javascript or server-side generation of the numbers.
Edit:
You really should do this via (in order of preference):
CSS numbering (see other answers)
Server-side (I don't do php - sorry)
client-side javascript should be a last resort:
<table id="numbered">
<tr>
<td>a</td>
<td>b</td>
</tr>
<tr>
<td>c</td>
<td>d</td>
</tr>
<tr>
<td>e</td>
<td>f</td>
</tr>
</table>
<script type="text/javascript">
var table=document.getElementById('numbered');
var tr=table.getElementsByTagName('tr');
for(var i=0; i<tr.length; i++)
{
var td=tr[i].getElementsByTagName('td');
td[0].insertBefore(document.createTextNode(i+1+'. '), td[0].firstChild);
}
</script>
As for me I am using while loop in a while loop (for php) If you wanted to get data from database.
Ex.
$query = mysql_query("SELECT * FROM table);
$getnumbers = mysql_num_rows($query);
$x=1; //initialize your number
while($x<=$getnumbers)
{
while($rows = mysql_fetch_assoc($query))
{
echo $x;echo $row["row1"];echo "<br>";
$x++ }
}

Categories