Jump to content

Sum of column in PHP/ MySQL - Help required for noob!


badgerchap

Recommended Posts

Sorry guys, I imagine this is as simple as simple can be.

 

I've only delved into PHP since this morning, and whilst it's actually gone pretty well so far, I'm absolutely stumped with the simplest of tasks. Here is my snippet:

 

<?php
$con=mysqli_connect("blahblahblah.....");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
 
$result = mysqli_query($con,"SELECT * FROM Basket");
echo "<table border='1'>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price (£)</th>
</tr>";
while($column = mysqli_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $column['Product'] . "</td>";
  echo "<td>" . $column['Quantity'] . "</td>";
  echo "<td>" . $column['Price'] . "</td>";
  echo "</tr>";
  }
echo "</table>";
 
 
mysqli_close($con);
?>
 
This is displaying the contents of a user's basket, and it's doing so just fine, with Product, Quantity and Price column being displayed perfectly. What I can't do, no matter how many of other people's snippets I try and tinker with and fit into my code, I just cannot get a total price for the basket to display. I'm sure there is a simple solution, I just can't work it out myself right now!
 
Any help greatly appreciated,
 
many Thanks,
 
Badgerchap

Your not far off! have alook at this and try to figure it out.

$totalPrice = 0;
echo "<table border='1'>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price (£)</th>
</tr>";
while($column = mysqli_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $column['Product'] . "</td>";
  echo "<td>" . $column['Quantity'] . "</td>";
  echo "<td>" . $column['Price'] . "</td>";
  echo "</tr>";

  $totalPrice += $column['Price'];
  }
echo "</table>";

echo $totalPrice;

Start by initiating a variable to hold the total price before the while loop. Inside the while loop, after you print the table row, increment the total price by column['price']. Once outside the while loop, echo the total price out.

 

$totalPrice += $column['Price'] is the same as $totalPrice = $totalPrice + $column['Price'];

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.