[英]PHP Session problem. When item is added it adds 1 to all of the items
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!
我已经为此苦苦挣扎了2天多,但我无法弄清楚!
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.
我想用 session 来解决这个问题。
<?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.这是第二页,这段代码是运行时你的select图片。 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>
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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.