How to get total during a foreach - php

I am learning PHP, and trying to output the total of the "Price" column.
Here's what it looks like right now:
http://imgur.com/X00o4jS
Here's the code:
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$food = $row["food"];
$price = $row["price"];
$id = $row['id'];
if(!empty($_POST[$id])){
$qtyPrice = $price * $_POST[$id];
$qty = $_POST[$id];
}
echo "<tr>
<td>$food</td>
<td>$qty</td>
<td>$$qtyPrice</td>
</tr>";
}

No need to do 2 loops. You are setting the array with the 1st while loop and then using a 2nd foreach loop just to read it and display the data.
It will be more efficient to use the while loop to generate your html table directly.
You can use $total += $qtyPrice (same as $total = $total + $qtyPrice).
Just remember to set it to 0 before the loop.
$total = 0;
while($row = $result->fetch_array()){
$food = $row["food"];
$price = $row["price"];
$id = $row['id'];
if(!empty($_POST[$id])){
$qtyPrice = $price * $_POST[$id];
$qty = $_POST[$id];
$total += $qtyPrice;
echo "<tr>
<td>$food</td>
<td>$qty</td>
<td>$$qtyPrice</td>
</tr>";
}
//display the total in its separate row
echo "<tr><td>Total:</td><td></td><td>$total</td></tr>";
Hope this helps!

set a variable before starting the loop, and adding the qtyPrice at it. Print that variable after exit the loop
$total = 0;
foreach($rows as $row){
$food = $row["food"];
$price = $row["price"];
$id = $row['id'];
if(!empty($_POST[$id])){
$qtyPrice = $price * $_POST[$id];
$total += $qtyPrice;
$qty = $_POST[$id];
}
echo "<tr>
<td>$food</td>
<td>$qty</td>
<td>$$qtyPrice</td>
</tr>";
}
echo $total;

Related

List shopping cart in phpmailer

I try to send an email with phpmailer after "Place Order".
The problem is that I cannot list the shopping cart as an email (product, quantity, price of each product and total price).
echo var_dump($_SESSION['cart']);
echo var_dump($_SESSION['qty_array']);
This shows me that everything seems to work.
cart.php:
<tr>
<?php
$total = 0;
if(!empty($_SESSION['cart'])){
include 'config.php';
$index = 0;
if(!isset($_SESSION['qty_array'])){
$_SESSION['qty_array'] = array_fill(0, count($_SESSION['cart']), 1);
}
$sql = "SELECT * FROM products WHERE id IN (".implode(',',$_SESSION['cart']).")";
$query = $conn->query($sql);
while($row = $query->fetch_assoc()){
?>
</tr>
<tr>
<td>
<img src="<?= $row['photo'] ?>" width="150px"><br />
<?= $row['name'] ?>
</td>
<input type="hidden" name="indexes[]" value="<?php echo $index; ?>">
<td>
<?php echo $_SESSION['qty_array'][$index]; ?>
</td>
<td>
<b><i class="fas fa-dollar-sign"></i> <?php echo number_format($_SESSION['qty_array'][$index]*$row['price'], 2); ?></b>
</td>
<?php $total += $_SESSION['qty_array'][$index]*$row['price']; ?>
</tr>
<?php
$index ++;
}
}
?>
phpmailer.php:
echo var_dump($_SESSION['cart']);
echo var_dump($_SESSION['qty_array']);
foreach($_SESSION['cart'] as $key => $product) {
$name = $product['name'];
$price = $product['price'];
$qty = $product['qty'];
$tprice = $product['totalPrice'];
}
$mail->Body = nl2br("$name\r\n$\r\n$qty\r\n$tprice");
This is not working at all. I tried a few things, and most of what worked was just the listing of the last product on the shopping cart list. But only the ID.
Edit:
I have tried another way, but still only the last item is listed.
phpmailer.php:
$total = 0;
if(!empty($_SESSION['cart'])){
include 'config.php';
$index = 0;
if(!isset($_SESSION['qty_array'])){
$_SESSION['qty_array'] = array_fill(0, count($_SESSION['cart']), 1);
}
$sql = "SELECT * FROM products WHERE id IN (".implode(',',$_SESSION['cart']).")";
$query = $conn->query($sql);
while($row = $query->fetch_assoc()){
$service = $row['name'];
$qty = $_SESSION['qty_array'][$index];
$qtyPrice = number_format($row['price'], 2);
$qtyTotalprice = number_format($_SESSION['qty_array'][$index]*$row['price'], 2);
$total += $_SESSION['qty_array'][$index]*$row['price'];
$mail->Body = nl2br("$service: ($qty) x ($$qtyPrice) = $$qtyTotalprice \r\n \r\nTOTAL: $ <u>$total</u>");
$index ++;
}
}
I found a solution:
phpmailer.php
...
$mail->Body = nl2br("Hi {$_POST['name']} \r\n");
/// List Cart Item(s) Start
$total = 0;
if(!empty($_SESSION['cart'])){
include 'config.php';
$index = 0;
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array_fill(0, count($_SESSION['cart']), 1);
}
$sql = "SELECT * FROM products WHERE id IN (".implode(',',$_SESSION['cart']).")";
$query = $conn->query($sql);
while($row = $query->fetch_assoc()){
$index;
$service = $row['name'];
$qty = $_SESSION['cart'][$index];
$qtyPrice = $row['price'];
$qtyTotalprice = number_format($_SESSION['cart'][$index]*$row['price'], 2);
$total += $_SESSION['cart'][$index]*$row['price'];
$mail->Body .= nl2br("$service: ($qty) x ($$qtyPrice) = $$qtyTotalprice \r\n");
$index ++;
}
}
$mail->Body .= nl2br(" \r\nTOTAL: $ <u>$total</u>");
/// Cart Item(s) End
$mail->Body .= nl2br("Kind regards \r\n");
...

PHP MySQL Dual While Loop giving me problems

I currently have a piece of code that I want to essentially pulls products quantity and prices and then give a grand total
The problem I have is the mathematics is way off... it's essentially multiplying the last quantity with the last price of the item during the loop (I hope I explained that with atleast half an ounce of clarity haha!)
Anyways here is the code, I think it was along the correct lines but somewhere I have gone wrong, Thanks!
<table>
<tr>
<th>Product Title</th>
<th>Nicotine Strength</th>
<th>Quantity</th>
<th>Price (inc. VAT)</th>
</tr>
<?php
$query = "SELECT `product`, `variant`, `quantity` FROM orders_detail WHERE order_id = '$orderid'";
$result = mysqli_query($con, $query);
$quantitytotal = 0;
while ($row = mysqli_fetch_assoc($result)) {
$product = $row['product'];
$stuff = $row['quantity'];
$variant = $row['variant'];
$linequantity = $stuff;
$quantitytotal += $stuff;
$pricequery = "SELECT product_price FROM products WHERE product_name = '$product'";
$priceresult = mysqli_query($con, $pricequery);
$pricetag = 0;
$priceline = 0;
while ($rowprice = mysqli_fetch_assoc($priceresult)) {
$price = $rowprice['product_price'];
$priceline = $price;
$pricetag += $price;
}
echo "Price: $pricetag<br>";
echo "Quantity: $quantitytotal<br>";
$linetotal = $priceline * $linequantity;
//echo "$product - $linequantity - $linetotal<br>";
echo '<tr><td>' . $product .' </td> ' . '<td>' . $variant . '</td>' . ' <td> ' . $linequantity . '</td>' . '<td> £' . $linetotal . '</td> </tr>';
}
$total = $pricetag * $quantitytotal;
?>
<tr><td>Total Ex Vat:</td><td> Total Inc Vat:</td></tr>
<tr><td><?php echo "£" . ($total / 1.2);?></td>
<td><?php echo "£" . $total; ?></td></tr>
</table>
You can calculate grand total by adding $linetotal in the loop.
$total=$total+$linetotal;
Initialize $total with 0 before loop.

Mysql row returns last value in array, but I expect the whole row

Here is my cart code:
function cart() {
$total = 0;
$item_quantity = 0;
$item_name = 0;
$item_number = 1;
$amount = 1;
$quantity = 1;
foreach ($_SESSION as $name => $value) {
if($value > 0 ) {
if(substr($name, 0, 8) == "product_"){
$length = strlen($name - 8);
$id = substr($name, 8 , $length);
$query = query("SELECT * FROM products WHERE product_id = " . escape_string($id)." ");
confirm($query);
$titleArr = array();
while($row = fetch_array($query)) {
$titleArr[$id] = $row['product_title'];
$product_name = implode(",", $titleArr);
$order_product = $product_name . "-". $value;
$sub = $row['product_price']*$value;
$item_quantity +=$value;
$item_number++;
$amount++;
$quantity++;
$id++;
}
$_SESSION['item_total'] = $total += $sub;
$_SESSION['item_quantity'] = $item_quantity;
$_SESSION['item_name'] = $order_product;
}
}
}
}
I searched online for a long time, please advise.
$_SESSION['item_name'] = $order_product;
It gives last value from fetch_array I want all product title on cart page.
Either of these changes should work...
This puts the m all into an array...
$_SESSION['item_name'] = array();
foreach ($_SESSION as $name => $value) {
...
$_SESSION['item_total'] = $total += $sub;
$_SESSION['item_quantity'] = $item_quantity;
array_push($_SESSION['item_name'],$order_product);
...
}
This puts them into a comma separated string...
$_SESSION['item_name'] = '';
foreach ($_SESSION as $name => $value) {
...
$_SESSION['item_total'] = $total += $sub;
$_SESSION['item_quantity'] = $item_quantity;
$_SESSION['item_name'] .= $order_product.', ';
...
}
$_SESSION['item_name'] = rtrim($_SESSION['item_name'],' ');
$_SESSION['item_name'] = rtrim($_SESSION['item_name'],',');
Please make two dimensional Array, if you want to show all product title on cart page.
Replace this
$order_product = $product_name . "-". $value;
with
$order_product[] = $product_name . "-". $value;
Before while loop assign the array:-
$order_product = array();
updated while loop
$total = 0
while($row = fetch_array($query)) {
$titleArr[$id] = $row['product_title'];
$product_name = implode(",", $titleArr);
$order_product = $product_name . "-". $value;
$sub = $row['product_price']*$value;
$item_quantity +=$value;
$item_number++;
$amount++;
$quantity++;
$id++;
$total += $sub;
$_SESSION['item_name'][] = $order_product;
}
$_SESSION['item_total'] = $total;
$_SESSION['item_quantity'] = $item_quantity;

Display images from a database into a PHP page

Im wondering what can I do to make images from a database on Php display on my page.
This is what I have
images .php
$query = "SELECT * FROM images ORDER BY name ASC ";
$result = $db->query($query);
$num_result = $result->num_rows;
echo "<h1> Images</h1>";
for ($i = 0; $i < $num_result; $i++){
$row = $result->fetch_assoc();
$name = $row['name'];
$URL = $row['imageURL'];
$array = array($URL);
}
foreach ($array as $image){
echo '<tr>';
echo '<td><img class="coupons" src="'.$image.'"/></td>';
echo '<td></td>';
echo '</tr>';
echo '<tr>';
}
This is just printing only one image and I have 10 in my database, what can I do or change to print all of the images from the database? Thanks
You should change
$array = array($URL);
into
$array[] = $URL;
And add before line:
for ($i = 0; $i < $num_result; $i++){
add line:
$array = array();
Try this,
$array = array();//initialize here
for ($i = 0; $i < $num_result; $i++){
$row = $result->fetch_assoc();
$name = $row['name'];
$URL = $row['imageURL'];
$array[] = $URL;
}
You can rewrite your code as,
while ($row = $result->fetch_assoc()){
$name = $row['name'];
$URL = $row['imageURL'];
echo '<tr>';
echo '<td><img class="coupons" src="'.$URL.'"/></td>';
echo '<td></td>';
echo '</tr>';
echo '<tr>';
}
$query = "SELECT * FROM images ORDER BY name ASC ";
$result = $db->query($query);
$num_result = $result->num_rows;
$array = array();
echo "<h1> Images</h1>";
for ($i = 0; $i < $num_result; $i++){
$row = $result->fetch_assoc();
$name = $row['name'];
$URL = $row['imageURL'];
$array[] = URL;
}
foreach ($array as $image){
echo '<tr>';
echo '<td><img class="coupons" src="'.$image.'"/></td>';
echo '<td></td>';
echo '</tr>';
}
You also had a trailing <tr> which may cause styling issues

PHP foreach() not looping through data as expected?

I have the foillowing PHP code, but I can't get it to work?
This is the main PHP file:
function get_data() {
$query = 'SELECT title, article FROM submissions';
$result = mysql_query($query);
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
++$i;
$row['i'] = $i;
$row['title'] = limittext($row['title'], 15);
}
return $row; //perhaps because $row is not return all?
}
$data = get_data();
require('template/data.inc.php');
?>
and this is template/data.inc.php:
<?php
foreach ($data as $value):
echo $data['i'].'<br>';
echo $data['title'].'<br>';
echo $data['article'].'<br>';
endforeach;
?>
template/data.inc.php is meant to output something like:
1 How to get your site on Google?
Text...
2 Secrets of SEO Revealed
Text...
My guess is get_data() is not returning the array() in a form which is supported within the foreach? - as its currently giving an error.
Here is your problem:
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
++$i;
$row['i'] = $i;
$row['title'] = limittext($row['title'], 15);
}
On every iteration, $row is being reset to current record, and in the end mysql_fetch_assoc will turn it to FALSE. You have to put each $row into auxiliary array and return it as whole resultset:
$i = 0;
$returnArray = array();
while ($row = mysql_fetch_assoc($result)) {
++$i;
$row['i'] = $i;
$row['title'] = limittext($row['title'], 15);
$returnArray[] = $row;
}
return $returnArray;
ANd in your template use $value to get details for each row:
foreach ($data as $value):
echo $value['i'].'<br>';
echo $value['title'].'<br>';
echo $value['article'].'<br>';
endforeach;
The way in which you're building $row and returning it
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
++$i;
$row['i'] = $i;
$row['title'] = limittext($row['title'], 15);
}
return $row;
}
You'll only EVER have the LAST iteration of $row set ... if that's what you want? In other words, $row will only continue a single value.
Your loop continues until $row has an value that is evaluated as false:
while ($row = mysql_fetch_assoc($result)) {
and then you return $row so you always return null or false!
replace
$row['title'] = limittext($row['title'], 15);
with
$row['title'] = limittext($row['title'], 15);
$result[]=$row;
and
return $row;
with
return $result;

Categories