-2

我正在练习 PHP,结果,我最终创建了一个虚拟的在线商店。我设法实现了大部分在线功能,但我在购物车上苦苦挣扎。

一旦用户登录并进入网站的产品区域,我希望用户能够将商品添加到购物车。我一直在关注phpAcademy YouTube 教程。我已经设法使用添加按钮/超链接显示所有产品,以将每个产品链接到名为 cart.php 的处理页面。每个按钮的链接与其关联的产品 ID 相匹配。

当我对此进行测试并单击“添加”时,产品的 ID 不会出现在 cart.php 页面上。

user_man_boxing_gloves.php:

<?php
session_start();

include('connect_mysql.php');

$product_name = 'product_name';
$product_qua = 'product_qua';
$product_price = 'product_price';
$product_image = 'product_image';
$product_des = 'product_des';

$get = mysql_query("SELECT product_id, product_image, product_name, product_des, product_price, product_type FROM products WHERE product_type='ManGloves' AND product_qua > 0 ORDER BY product_id DESC");
if(mysql_num_rows($get) == 0)
{
    echo "There are no Products to display";
}
else
{
    ?>
    <?php
    while($get_row = mysql_fetch_assoc($get))
    {
        ?>
        <table id='display'>
            <tr><td><?php echo "<img src=$get_row[$product_image] class='grow'>" ?></td></tr>

            <tr>
                <th></th>
                <th><strong>Avalible</strong></th>
                <th><strong>Price</strong></th>
                <th><strong>Description</strong></th>
            </tr>

            <tr>
                <td width='290px'><?php echo "$get_row[$product_name]" ?></td>
                <td width='290px'><?php echo "$get_row[$product_qua]" ?></td>
                <td width='290px'><?php echo "$get_row[$product_price]" ?></td>
                <td width='290px'><?php echo "$get_row[$product_des]" ?></td>
            </tr>
            <tr>
                <td><?php echo '<a href="cart.php?add=' . $get_row['product_id'] . '">Add</a>'; ?></td>
            </tr>
        </table>

        <?php
    }
}
?>

购物车.php:

<?php

if(isset($_GET['add'])){
    $_SESSION['cart_'.$_GET['add']]+='1';

}

echo $_SESSION['cart_'];

?>

我想显示产品 ID 以查看我的代码是否有效,并且我想在验证它是否有效后进行进一步处理。

在此处输入图像描述

查看屏幕截图,添加按钮似乎正确显示了产品 ID。

4

1 回答 1

0

看起来 cart.php 中的问题涉及以下代码段:

if(isset($_GET['add'])){
        $_SESSION['cart_'.$_GET['add']]+='1';
}

解决这个问题,这意味着如果 ID 为 1,您可以在会话数组中看到以下内容:

$_SESSION['cart_1'] = 1;
$_SESSION['cart_2'] = 4;

对于显示器,您可能想要的是将数组存储到购物车中。那是,

if(isset($_SESSION['cart']))
{
    $arr = unserialize($_SESSION['cart']);
}
else
{
    $arr = array();
}

if(isset($_GET['add'])){
        $arr[$_GET['add']] += 1;
}
$_SESSION['cart'] = serialize($arr);

var_dump(unserialize($_SESSION['cart']));
于 2013-03-14T00:45:06.087 回答