There are a couple of linked issues here. Your cart
function is effectively:
function cart() {
//print some stuff
foreach($_SESSION as $name => $value) {
if (empty($total)) {
if (empty($sub)) {
//do nothing
} else {
$total = $sub;
}
} else {
$total += $sub;
}
}
}
You're setting a variable called $total
inside your function, but PHP treats that as what's called a local variable - that's a variable that exists within the function itself, but not outside of it. Likewise, variables that are set outside the function can't be used inside it unless you explicitly make them available - this is called variable scope.
There are a few ways to access variables set inside functions. Since you're using $_SESSION
already, I'd suggest using this:
function cart() {
$total = 0;
//print some stuff
foreach($_SESSION as $name => $value) {
if (! empty($sub)) {
$total += $sub;
}
}
$_SESSION['total'] = $total;
}
I'm initialising $total
at the start of the function, so you don't need to check if it exists before trying to add to it. I'm also setting a variable in the session, which you can use outside the function.
Secondly - you need to call your function before you can use it. None of your code above is calling your function - all you need to do is have a line with cart();
on it.
Then, when you're setting the variables for the database, you can use:
$name = $_POST['name'];
$total = $_SESSION['total'];
A couple of other things - mysql_
functions are deprecated, and will be removed from a future version of PHP. You shouldn't really be using them for new code now - mysqli_
functions are fairly easy to switch to, and let you use prepared statements, which help you make your code more secure; and there's also the PDO
library, which isn't as direct to switch code over to, but which isn't tied in to a specific database.
Also - and this is a personal preference - your cart()
function is printing out the contents of the cart, as well as doing some calculations on it. I try to have functions that do one single thing, rather than lump them together, even if they do fit. In this case, you could have a print_cart()
function and a get_cart_total()
function - I find that it's a lot easier to maintain code that's written that way.