Reputation: 186
I am making a shopping cart where when you click on either of two cars you add that item to the shopping cart. The problem is that when I click for example on the BMW picture the count goes up for both BMW and Toyota. I've been struggling on this for over 2 days now and I can't figure it out!
Here is my first page. When I click on either of pictures I want it to add it to the shopping cart. I want to use session to work this out.
<?php session_start(); ?>
<?php include('navbar.php');?>
<h1>OstosKoriTori</h1>
<h3>Click the picture to add the car to your shopping cart!</h3>
<p>Toyota Chaser JZX 100</p>
<p>BMW E92</p>
<div class="autot">
<a href="add-basket.php?id=chaser"><img src="chaser.jpg" alt="Chaseri"></a>
<a href="add-basket.php?id=bmw"><img src="bmw.jpg" alt="Bemari"></a>
<br>
</div>
Here is the second page, this code is run when you select the picture. I believe the problem is here.
<?php session_start(); ?>
<?php
if(!isset($_SESSION['chaser'])){
$_SESSION['chaser'] = 0;
}
if(isset($_SESSION['chaser'])){
$_SESSION['chaser'] += 1;
}
if(!isset($_SESSION['bmw'])){
$_SESSION['bmw'] = 0;
}
if(isset($_SESSION['bmw'])){
$_SESSION['bmw'] += 1;
}
?>
<?php
header("Location: http://" . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']) . '/'
. "basket-session.php");
?>
And here is the last page where you can see how many cars you have depending on how many times you clicked on the picture.
<?php session_start(); ?>
<?php include('navbar.php')?>
<h1>OstosKoriTori</h1>
<h3>Ostoskorin sisältö</h3>
<p>Toyota Chaser JZX 100</p>
<p>BMW E92</p>
<div class="kuvat">
<img src="chaser.jpg" alt="Chaseri">
<img src="bmw.jpg" alt="Bemari">
</div>
<div class="kpl">
<p><?php echo "Korissa on: <strong>" . $_SESSION['chaser'] . "</strong> kpl"; ?></p>
<p><?php echo "Korissa on: <strong>" . $_SESSION['bmw'] . "</strong> kpl"; ?></p>
</div>
<div class="clearBasket">
<a href="clear-basket.php">Tyhjennä ostoskori</a>
</div>
Upvotes: 1
Views: 46
Reputation: 17378
Based on the code you've posted, something like this should work. I've added some comments to explain the code.
<?php
session_start();
// Initialise session to existing value or zero
$_SESSION['chaser'] = $_SESSION['chaser'] ?? 0;
$_SESSION['bmw'] = $_SESSION['bmw'] ?? 0;
// Determine selected car
$car = $_GET['id'] ?? null;
// Increment selected car
if ($car) {
$_SESSION[$car] += 1;
}
header('Location: http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/basket-session.php');
Upvotes: 1