PHP MySQL购物车 - 向会话添加项目

时间:2013-03-14 00:28:21

标签: php mysql

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

用户登录并进入网站的产品区域后,我希望用户能够将商品添加到购物车。我一直关注phpAcademy YouTube tutorial。我已设法显示所有产品的添加按钮/超链接,以将每个产品链接到名为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
    }
}
?>

cart.php:

<?php

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

}

echo $_SESSION['cart_'];

?>

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

enter image description here

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

1 个答案:

答案 0 :(得分: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']));
相关问题