Calculate total price inside php table - php

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>

Related

How to list the records in horizontal order using modulus (%) operation?

I have problem in my task where I suppose to display my record in horizontally with 3 columns
Unfortunately, my display is become vertical.
The task require us to use modulus (%) operator in order to display the records. The records are stored in database (id, title, picture, category, author). There are 11 books that store in database. Here is my PHP code:
<?php
include_once('config.php');
$result = mysqli_query($mysqli, "SELECT * FROM books ORDER BY id ASC");
?>
<style>
img {
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
width: 200px;
}
.p2 {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
padding-left: 10px;
}
.p3 {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
padding-left: 10px;
color: blue;
}
</style>
<div class="container">
<center>
<h1>Koleksi Buku Peribadi</h1>
<table>
<?php
$x=11;
$y=3;
$i=$x % $y;
while($i && $book = mysqli_fetch_array($result)) {
?>
<tr>
<td>
<img src="Gambar-buku/<?php echo $book['picture'];?>">
<p class='p2'>Penulis:<span class='p3'> <?php echo $book['author'];?> </span>
<br> <i><?php echo $book['category'];?></i>
</p>
<center><button type="button">Details</button> </center>
</td>
</tr>
<?php
$i++; }
?>
</table>
</center>
</div>
Modulus is useful when you need to equally divide items into several categories.
Formally: index_of_category = index_of_item % number_of_categories
Practically: In your case, you have 3 categories (columns). For item with index i, you find index of its column with i % 3.
For making table layout work, you then need to:
print tr opening tag for every item belonging in column with index 0
print tr closing tag for every item belonging in column with index 2.
In my example, you can change number of columns easily by modifying $numberOfColumns variable.
<div class="container">
<center>
<h1>Koleksi Buku Peribadi</h1>
<table>
<?php
$numberOfColumns = 3;
for ($i = 0; (($book = mysqli_fetch_array($result)) !== null); $i++) {
$printRowOpeningTag = $i % $numberOfColumns === 0;
$printRowClosingTag = $i % $numberOfColumns === $numberOfColumns - 1;
if ($printRowOpeningTag) {?>
<tr>
<?php } ?>
<td><img src="Gambar-buku/<?php echo $book['picture'];?>">
<p class='p2'>Penulis:<span class='p3'> <?php echo $book['author'];?> </span>
<br> <i><?php echo $book['category'];?> </i>
</p>
<center><button type="button">Details</button> </center>
</td>
<?php if ($printRowClosingTag) { ?>
</tr>
<?php } ?>
<?php
} ?>
</table>
</center>
</div>

How to style a table that is part html and part php

I found it hard to phrase this question but I will try my best. I am creating a php and MYSQL leaderboard, it all works but now I want to style it. I don't know very much css and this might be a simple fix. I am trying to style the table so that all the data table elements sit symmetrical like a table should be, and aligned to the center of the headers. I think it is not working because I technically have 2 tables I am trying to style and they are not working in conjunction with each other. Here is the code and forgive my usernames in the table, I get lazy sometimes.
<!DOCTYPE html>
<html>
<head>
<title>Leaderboards</title>
<style type="text/css">
th {
overflow: auto;
font-size: 25px;
border: 1px solid;
padding: 5px;
margin: 2px 2px 2px 2px;
}
td {
font-size: 25px;
padding-left: 30px;
padding-top: 3px;
}
</style>
</head>
<body>
<h1>Leaderboard</h1>
<table>
<tr>
<th>Rank</th>
<th>User</th>
<th>Score</th>
</tr>
</table>
<?php
include 'HytecFunctions.php';
$conn=connectDB();
$rank = 1;
$sql = 'SELECT Name, Score FROM Names ORDER BY Score DESC';
foreach ($conn->query($sql) as $row) {
echo "<table>
<td>$rank</td>
<td>$row[Name]</td>
<td>$row[Score]</td>
</tr>
</table>";
$rank++;
}
$conn->close();
?>
</body>
</html>
The table as it shows in my browser
Because you try to create another table every loop. Try to put them all in a single table.
<table>
<tr>
<th>Rank</th>
<th>User</th>
<th>Score</th>
</tr>
<?php
include 'HytecFunctions.php';
$conn=connectDB();
$rank = 1;
$sql = 'SELECT Name, Score FROM Names ORDER BY Score DESC';
foreach ($conn->query($sql) as $row) {
echo '<tr>
<td>'.$rank.'</td>
<td>'.$row["Name"].'</td>
<td>'.$row["Score"].'</td>
</tr>';
$rank++;
}
$conn->close();
?>
</table>
Note: Don't mind much the way I input your $row variables. Yours will still work even if you use double tick (") to display rows. I just use a single tick (') to display your data as is to have a much cleaner look on your code. Refer here for the difference.

give color to specific row of a table acc. to situation

I created a table from database column name "Do You have passport" user answers in yes or no I want where user answer is yes that row should be green and row where user answer is no that row is white can any one tell me how can I apply css to this table that works dynamically.
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
</html>
<?php
$conn = new mysqli("localhost","root","","db_dat");
$havepassport='';
$sql="SELECT * from upload;
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$havepassport.='<table>'.'<tr>'.'<td>';
$havepassport.=$row['having_passport'];
$havepassport.='</table>'.'</tr>'.'</td>';
echo $havepassport;
}
?>
You are doing it wrong. Your while add new table to HTML. So, if you have 100 rows, 100 tables will be added to DOM instead of rows.
Use following:
PHP
$sql = "SELECT * from upload";
$result = $conn -> query($sql);
$havepassport = '<table>';
while ($row = $result -> fetch_assoc()) {
$passportClass = $row['having_passport'] == 'Yes' ? 'green' : 'red';
// ^^^^^^^^^^^ Getting classname depending on the passport value
$havepassport .= '<tr class='.$passportClass.'>'.
// ^^^^^^^^^^^^^^ Add Class Here
'<td>';
$havepassport. = $row['having_passport'];
$havepassport .= '</td>'.
'</tr>';
}
$havepassport .= '</table>';
echo $havepassport;
CSS:
.green {
background: green;
}
.red {
background: red;
}
Try this:
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
</html>
<?php
$conn = new mysqli("localhost","root","","db_dat");
$havepassport='';
$sql="SELECT * from upload;
$result = $conn->query($sql);
$havepassport.='<table>';
while($row = $result->fetch_assoc()) {
$passHaveClass = '';
if($row['having_passport'] =="yes"){
$passHaveClass = "greenColor";
}
$havepassport.='<tr class='.$passHaveClass.'>';
$havepassport.= '<td>'.$row['having_passport'].'</td>';
$havepassport.='</tr>;
}
$havepassport.='</table>';
echo $havepassport;
?>
the greenColor class having bg color is green.
checkout this fiddle : https://jsfiddle.net/knkp02Ld/1/
HTML
<table id="mytable">
<tr>
<td>User Name</td>
<td>Yes</td>
</tr>
<tr>
<td>User id</td>
<td>No</td>
</tr>
<tr>
<td>Whatever</td>
<td>Yes</td>
</tr>
</table>
JS
$('#mytable td:contains("Yes")').parent().css('background', 'green');
$('#mytable td:contains("No")').parent().css('background', 'red');
Select all elements that contain the specified text.
docs: https://api.jquery.com/contains-selector/
Edit
Other way you can use .each function like as follows
$('#mytable td').each(function() {
var value = $(this).html();
if (value == "Yes") {
$(this).parent().css("background", "red");
}
});

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

How to put images on a 3 by 3 table?

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).

Categories