(PHP) Shopping Cart



我正试图用PHP创建一个购物车,但一旦用户离开购物车区域,所有产品都会消失。这就是我要做的:

<?php foreach($almofadas as $almofadas):?>
<form action="cart.php" method="GET">
<div class="base col-6 col-sm-4 col-md-5 col-lg-4 col-xl-4">
<div class="card">
<img src="uploads/<?php echo $almofadas['imagem'];  ?>" alt="">
<div class="content-c">
<div class="row-p">
<div class="details">
<span><?php echo $almofadas['pnome'] ; ?></span>
</div>
<div class="price">R$ <?php echo $almofadas['preço'];?> </div>
</div>
<input type="hidden" name="id" value="<?php echo $almofadas['p_id']?>">
<div style="margin-top: 10px;">
<div style="margin-bottom: 5px;"><button class="buttons-1" data-toggle="modal" data-target="#myModal">Detalhes</button></div>
<div><button class="buttons-2" type="submit">Adicionar ao Carrinho</a> </button></div> 
</div>
</div>
</div>
</div>
</form>
<?php endforeach;  ?>

现在的推车系统:

<?php
session_start();

require_once 'conn.php';

$_SESSION['id'] =  $_GET['id'];
$result_pedido = "SELECT * FROM tb_produtos WHERE p_id = '{$_SESSION['id']}'"; 
$resultado_pedido = mysqli_query($conn, $result_pedido);
$pedidos = mysqli_fetch_all($resultado_pedido, MYSQLI_ASSOC);

?>

在这里,我只能添加一个产品,而且我不能将其保存到$_SESSION中,因为我说过一旦我离开购物车,产品就会消失。

<?php foreach($pedidos as $pedidos):?>
<tr>
<td>
<div class="cart-img">
<img src="uploads/<?php echo $pedidos['imagem'];?>" width="125px">
</div>
</td>
<td>
<div class="cart-model">
<?php echo $pedidos['pnome'] ; ?>
</div>
</td>
<td>
<div class="cart-quantity">
<input class="i-quantity" type="number" value="1">
</div>
</td>
<td>
<div class="cart-price">
R$<?php echo $pedidos['preço'] ; ?>
</div>
</td>
</tr>
</tbody>
</table>
<?php endforeach; ?>

如果您选中这一行:

$_SESSION['id'] =  $_GET['id'];

这意味着";id";中的$_SESSION始终设置为$_GET['id'],即使它是空的。因此,每次用户访问页面时都会重置它。

您应该:

  1. 有一些机制来存储您的购物车内容。您的代码中没有;以及
  2. 在将新id存储到购物车之前,有一种方法可以检查用户是否访问了该id

例如,

<?php
/**
* This only make sense if this script is called
* by some AJAX / javascript interaction to specifically
* add a new item to cart.
*/
session_start();
require_once 'conn.php';
if (isset($_GET['id']) && !empty($_GET['id'])) {
$_SESSION['id'] =  $_GET['id'];
}
$result_pedido = "SELECT * FROM tb_produtos WHERE p_id = '{$_SESSION['id']}'"; 
$resultado_pedido = mysqli_query($conn, $result_pedido);
$pedidos = mysqli_fetch_all($resultado_pedido, MYSQLI_ASSOC);
// If the user visits a path where the $_GET['id'] have result in
// database and the user specified that he / she want to save something
// to his / her cart.
if (isset($_GET['id']) && !empty($_GET['id']) && !empty($pedidos)) {
if (!isset($_SESSION['cart'])) $_SESSION['cart'] = []; // initialize if not exists.
$_SESSION['cart'] = array_merge($_SESSION['cart'], $pedidos);
}

?>

注意:应该以某种方式将数量设置为购物车。您需要更改数据结构以设置或增加";数量";。但这至少是一个开始。

最新更新