How can I add together MySQL content?

Hello,

I am putting together an online ordering system for a restaurant and have all the information for each item saved in a MySQL database. When you are reviewing your selected items I need it to add together the prices of all the items you checked off on the selections page to get the order’s total price and display it.

Here is the code I have so far:

<?php
$item=$_POST['title'];
foreach ($item as $itemname)
{
	
$query = mysql_query("SELECT * FROM `menu` WHERE title = '$itemname'");
	while($row = mysql_fetch_array($query)) {
		
echo "<p>" . $row['title'] . " - <span style=color:#000;>$" . $row['price'] . "</span></p>";
	}
}
echo "<h3>ORDER TOTAL: </h3>";


?>

It needs to add together the $row[‘price’] values together for each item that is selected. Multiple items can be chosen.

Any help is highly appreciated! :slight_smile:

$total = $total + $row[‘price’];

^ within the loop

If this site ever becomes popular, you’ll regret putting database queries in loops, it’ll kill the site under load.

Dan’s right (as always :p), you can pull all the required records out in one query, even the total too. (See SUM() in the MySQL docs)


$sql = sprintf(
    "SELECT title, price FROM menu WHERE title IN ('%s')",
    implode(
        "','",
        array_map(
            'mysql_real_escape_string',
            (array)$_POST['title']
        )
    )
);

You are passing an array of items in a form?

Then you can just implode() the array and SELECT SUM()

eg


$array = (1, 3, 6, 44);
$query = "SELECT SUM(price) WHERE id IN (".implode(',' $array).")";

btw

$query = mysql_query("SELECT …

$query is actually a result, so that just makes things harder to read

edit: lol should refresh more …