I created an object, it’s named carwash. I created a session and assigned that object for session, if I enter quantity then and press buy button, I have result (example 6):
Your shopping cart contains 6 items.
but when I enter nothing, I get:
Your shopping cart contains items.
How should I do? Thank you! Here is all my code:
index.php
<?php
session_start();
require_once 'carwash.php';
if (isset($_SESSION['encoded_cartopass'])) {
// first let's get the variable from the session
$encoded_cartopass = $_SESSION['encoded_cartopass'];
// now let's unpack it
$cartopass = unserialize($encoded_cartopass);
// echo quantity
echo "Your shopping cart contains {$cartopass->getQuantity()} items. <br /><br />";
}
else {
echo "Your shopping cart contains 0 items. <br /><br />";
}
?>
<form action="process.php" method="post">
Quantity: <input type="text" name="quantity" id="quantity"/>
<input type="submit" value="Buy" name="submit" />
</form>
process.php
<?php
require_once 'carwash.php';
if (isset($_POST['submit'])) {
if (!isset($_SESSION['encoded_cartopass'])) {
// construct and set quantity
$cartopass = new carwash();
$cartopass->setQuantity($_POST['quantity']);
// construct and encode session
session_register('encoded_cartopass');
$_SESSION['encoded_cartopass'] = serialize($cartopass);
}
else {
// if session is existing, decode it and
// increment quantity
$encoded_cartopass = $_SESSION['encoded_cartopass'];
$cartopass = unserialize($encoded_cartopass);
$cartopass->incrementQuantity($_POST['quantity']);
// encode class and assign to session and
// session is used pass to index.php
$_SESSION['encode_cartopass'] = serialize($cartopass);
}
}
echo "<script>window.location.href='index.php'</script>";
?>
carwash.php
<?php
class carwash {
private $carmake;
private $caryear;
private $quantity;
public function getCarmake() {
return $this->carmake;
}
public function setCarmake($carmake) {
$this->carmake = $carmake;
}
public function getCaryear() {
return $this->caryear;
}
public function setCaryear($caryear) {
$this->caryear = $caryear;
}
public function getQuantity() {
return $this->quantity;
}
public function setQuantity($quantity) {
$this->quantity = $quantity;
}
public function incrementQuantity($quantity = '') {
if (empty($quantity)) {
$this->quantity++;
}
else {
$this->quantity += $quantity;
}
}
public function washcar() {
echo "scruba, dub, dub, scruba, dub, dub <br />";
echo "I'm feelling cleaner, Thank you!";
}
}
?>