PHP MySQL Dual While Loop giving me problems - php

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.

Related

How can I display data which are the addition of all "Price" multiply with "amountt"?

I cant get the idea on how to get "Total Price" by adding all of the rows which are multiplication of "Price" and "amount"
if($result->num_rows > 0){
while($row = $result-> fetch_assoc()){
echo "<tr><td>" . $row["FoodID"] . "</td><td>" . $row["Foodname"] . "</td><td>" . $row["Price"] . "</td><td>" . "<input type='number' min='0' id='amountt' />" . "</td><td>";
}
}
else {
echo "No Results Found.";
}
echo "<label for='amountt'>Total Price = </label>" . $row["Price"] * "value[id='amountt']";
$conn->close();
?>
If you have rows of price and amount, you can calculate the product price by multiplying price and amount. The product price will just be the price of one product (but can be multiple items). And to get total price you can sum all product prices together.
For example,
$totalPrice = 0;
foreach($rows as $row) {
$productPrice = $row['price'] * $row['amount'];
$totalPrice = $totalPrice + $productPrice;
}
Then you can apply this loop to your problem. You can create a new variable $productPrice and $totalPrice or you can omit $productPrice altogether like below.
$totalPrice = $totalPrice + ($row['price'] * $row['amount']);
or just
$totalPrice += $row[['price'] * $row['amount'];

Colour Table Cell Based on Value with PHP

I generate a html table from a mysql query and am wanting to colour cells based on the value of .$result->Games.. For argument sake, if the value of games is less than 10 I'd like the cell to be red and if it is greater than 40 I'd like the cell to be green. I'd also like to be able to colour anything between 10 and 40 as yellow.
There are a few questions already out there but I've not been able to modify any of the answers to suit this application. I'm thinking I may have to use an if function and couple it with bgcolor="#008000" for example but I'm not sure how to incorporate this into the codes snippet below.
$select = $_POST['correlation'] ?: '447';
$myQuery = $wpdb->get_results('SELECT * FROM ' . 'afl_player_correlations' . ' WHERE Player_ID = '. $select . ' AND COV >= 0 ORDER BY ' . COV . ' DESC');
if($myQuery){
echo '<div style="overflow-x:auto;">';
echo '<table class="splits">';
echo "<tr>";
echo "<th>Teammate</th>";
echo "<th>Games</th>";
echo "<th>Co-Variance</th>";
echo "</tr>";
foreach ( $myQuery as $result )
{
echo '<tr><td>'.$result->Teammate.'</td><td>'.$result->Games.'</td><td>'.$result->COV.'</td></tr>';
}
echo '</table>';
echo '</div>';
}
<?php
$select = $_POST['correlation'] ?: '447';
$myQuery = $wpdb->get_results('SELECT * FROM ' . 'afl_player_correlations' . ' WHERE Player_ID = '. $select . ' AND COV >= 0 ORDER BY ' . COV . ' DESC');
if($myQuery){
?>
<div style="overflow-x:auto;">
<table class="splits">
<tr>
<th>Teammate</th>
<th>Games</th>
<th>Co-Variance</th>
</tr>";
<?php
foreach ( $myQuery as $result )
{
if( $result->Games < 10 ){
$color = 'red';
}else if( $result->Games > 40 ){
$color = 'green';
}else{
$color = 'yellow';
}
?>
<tr>
<td><?php echo $result->Teammate;?></td>
<td style="background-color: <?php echo $color;?>"><?php echo $result->Games;?></td>
<td><?php echo $result->COV;?></td>
</tr>
<?php
}
?>
</table>
</div>
<?php
}
?>
foreach ( $myQuery as $result )
{
$style = "background-color: ";
if ($result->Games < 10) {
$style .= "red;";
}
else if ($result->Games < 40) {
$style .= "yellow;";
}
else{
$style .= "green;";
}
echo '<tr><td>'.$result->Teammate.'</td><td style="$style">'.$result->Games.'</td><td>'.$result->COV.'</td></tr>';
}

Deleting an item from my shopping cart using PHP and MySQL

I'm just learning how to use this StackOverflow, so please bear with me. If you need anything further I can provide it. I can click the checkmark on your answer if you can help me.
My code is working, but there is a small glitch. Currently, I have $i=0 and my code deletes the $i from the form. The problem is that with, for example, when $i=2 is deleted, $i=3 becomes $i=2, and I can no longer delete that item from my cart, because it is now the same $i that was deleted.
Here is my code:
if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "") {
// Access the array and run code to remove that array index
$key_to_remove = $_POST['index_to_remove'];
if (count($_SESSION["cart_array"]) <= 1) {
unset($_SESSION["cart_array"]);
header("location: cart.php");
} else {
unset($_SESSION["cart_array"]["$key_to_remove"]);
//sort($_SESSION["cart_array"]);
}
}
And here is my output loop:
$cartoutput = "";
$cartTotal="";
$totalwithtaxdisplay = 0;
$servicechargedisplay =0;
$grandtotaldisplay = 0;
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$cartoutput = "<div align='center'><font style='font-weight: bold; font-size: 20pt;'>Your order is currently empty.</font></div>";
}else{
$i=0;
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
$result = mysqli_query($con,"SELECT * FROM menuitem WHERE id='$item_id' LIMIT 1");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));// Displays the error that mysql will generate if syntax is not correct.
exit();
}
//echo mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
//item id is $each_item['item_id']; being pulled in from form on other page PID.
$id = $row['id'];
$product_name = $row["name"];
$price = $row["price"];
$description = $row['description'];
}
$tax = .065;
$service = .18;
$pricetotal = $price * $each_item['quantity'];
$cartTotal = $pricetotal + $cartTotal;
$totalwithtax = round($cartTotal + ($cartTotal * $tax), 2); //Order Items + Tax
$totalwithtaxdisplay = number_format($totalwithtax, 2, '.', ''); //displays the decimals correctly
$servicecharge = round($totalwithtax * $service, 2); //service charge
$servicechargedisplay = number_format($servicecharge, 2, '.', ''); //displays the decimals correctly
$grandtotal = round($totalwithtax + ($totalwithtax * $service), 2); //service charge
$grandtotaldisplay = number_format($grandtotal, 2, '.', ''); //displays the decimals correctly
$cartoutput .= " <tr><td width='20%'> Order Item $i </td>
<td width='40%'> " . $product_name . "</td>
<td width='20%'> $" . $price . ".00</td>";
$cartoutput .=" <td width='20%'><form action='cart.php' method='post'>
<input name='deleteBtn" . $item_id . "'type='submit' value='Remove This Item' />
<input name='index_to_remove' type='hidden' value='" . $i . "' />
</form></td></tr>";
$i++;
}
}
I echo out the $cartouput at a later time. You can see in the code above the second $cartouput is the form i'm using. It hold the value $i, but when that value is deleted, it doesn't let me delete the item that has updated into the new $i.
Instead of setting index_to_remove to $i, you should set it to $item_id and in your session variable. That way, you no longer need $i.
Also, this line leaves you with an SQL injection vulnerability: $item_id = $each_item['item_id'];. You should, at minimum, escape it using mysqli_real_escape_string().

Using Substr in a While loop for multiple products

I am trying to show only part of my items details and have implemented substr into my while loop. However it works for my first product, but my second product only shows the '...' and not the first 7 characters
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
if (strlen($details) > 10){
$details1 = substr($details, 0, 7) . '...';
} else {
$details1 = $details;
}
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$dynamicList .= '<div class="contentImage"><img src="images/stock_images/' . $id . '.png" alt="' . $product_name .'" width="136" height="97"></div>
<div class="contentDes"><strong>' . $product_name .'</strong><br>
Price: £' . $price .'<br>
' . $details1 . '<br>
View Product</div>';
}
Either make this:
if (strlen($details) > 7){
$details1 = substr($details, 0, 7) . '...';
}
OR
if (strlen($details) > 10){
$details1 = substr($details, 0, 10) . '...';
}

Displaying shopping cart in table

Think I've done this completely wrong but I am trying to display the values of the items when added to the shopping cart into a table. My code looks like this:
<?php
function minicart() {
foreach($_SESSION as $name => $value) {
if ($value > 0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name) -5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
'<table border = "1">'
'<tr>'
'<td>'<echo $get_row['name'].' x '.$value.' # £'.number_format($get_row['price'], 2).' = £'.number_format($sub, 2).' [-] [+] [Delete]<br />''</tr>';
'</tr>'
'</table>'
}
}
$total += $sub;
}
}
if ($total==0) {
echo "Your cart is empty";
}
else {
echo '<br />Total: £'.number_format($total, 2);
?>
Try this:
function minicart()
{
$items = 0;
$tbl = array();
foreach($_SESSION as $name => $value)
{
if ($value > 0) {
if (substr($name, 0, 5)=='cart_')
{
$id = substr($name, 5, (strlen($name) -5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
$tbl[] = '<table border="1"><thead><tr>'
. '<th>Item</th>'
. '<th>Quantity</th>'
. '<th>Unit Price</th>'
. '<th>SubTotal</th>'
. '<th>Action</th>'
. '</tr></thead><tbody>'
;
while ($get_row = mysql_fetch_assoc($get)) {
$items++;
$sub = $get_row['price'] * $value;
$tbl[] = '<tr>'
. '<td>' . $get_row['name'] . '</td>'
. '<td>' . $value . '</td>'
. '<td>£' . number_format( $get_row['price'], 2 ) . '</td>'
. '<td>$pound;' . number_format( $sub, 2) . '</td>'
. '<td>'
. ' [-] '
. ' [+] '
. ' [Delete]'
. '</td>'
. '</tr>'
;
}
$tbl[] = '</tbody>';
}
$total += $sub;
}
}
if ($items==0)
{
echo "Your cart is empty";
}
else
{
$tbl[] = '<tfoot><tr>'
. '<td colspan="3" style="text-align:right; font-weight:bold">Total:</td>'
. '<td>£' . number_format($total, 2) . '</td></tr></tfoot></table>';
echo implode( "\n", $tbl );
}
}
I changed the logic so that if the item count is zero, it displays the "empty cart" message, allowing for zero-cost items.
I tried to re write your table to correct format:
echo '<table border = "1">';
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
echo '
<tr>
<td>'.
$get_row['name'].' x '.$value.' # £'.number_format($get_row['price'], 2).' = £'.number_format($sub, 2).'
[-]
[+]
[Delete]<br />
</td>
</tr>
';
}
echo '</table>';
Please see PHP Strings
I think you want to replace the if-statement with the following.
This will give you 1 table with a row per item, probably what you're looking for.
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name) -5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
echo '<table border = "1">';
echo '<tr>';
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
echo '<td>';
echo $get_row['name'].' x '.$value.' # &pound';
echo number_format($get_row['price'], 2).' = &pound';
echo number_format($sub, 2);
echo '[-] ';
echo '[+] ';
echo '[Delete]<br />';
}
echo'</tr>';
echo'</table>';
}

Categories