【问题标题】:Creating an order cart - clicking on "view cart" clears the session and reloads page?创建订单购物车 - 单击“查看购物车”会清除会话并重新加载页面?
【发布时间】:2011-08-07 11:02:35
【问题描述】:

我在使用允许用户浏览从 MySQL 表中提取的产品的简单脚本时遇到问题。

该脚本具有“购物车”功能,用户可以在其中将特定商品添加到订单中。然后,用户可以查看订单,该订单会生成已订购的特定商品的列表、它们的价格和总金额。 (稍后用户将能够通过电子邮件将输出发送给网站创建者)

这里是控制器:

<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/includes/config.php';
require_once($docRoot . '/includes/layout.php');
require_once($docRoot . '/includes/magicquotes.inc.php');

$productsQuery = 'SELECT `id`, `refCode`, `desc`, `pack`, `measure`, `quantity`, `deptCode`, `taxable`, `price1`, `price2`, `crdCode`, `cost1`, `cost2` FROM `products` ORDER BY `desc` ';
$productsSql = mysql_query($productsQuery) or die(mysql_error());

session_start();
if (!isset($_SESSION['order']))
{
$_SESSION['order'] = array();
}

if (isset($_POST['action']) and $_POST['action'] == 'Order')
{
// Add item to the end of the $_SESSION['order'] array
$_SESSION['order'][] = $_POST['id'];
header('Location: .');
exit();
}

if (isset($_POST['action']) and $_POST['action'] == 'Clear order')
{
// Empty the $_SESSION['order'] array
unset($_SESSION['order']);
header('Location: ?order');
exit();
}

if (mysql_num_rows($productsSql) == 0)
{
die('No results.');
} else
{
$orderContent = '';
while($row = mysql_fetch_assoc($productsSql))
{
$prId = $row['id'];
$prRefCode = $row['refCode'];
$prDesc = $row['desc'];
$prPack = $row['pack'];
$prMeasure = $row['measure'];
$prQuantity = $row['quantity'];
$prDeptCode = $row['deptCode'];
$prTaxable = $row['taxable'];
$prPrice1 = $row['price1'];
$prPrice2 = $row['price2'];
$prCrdCode = $row['crdCode'];
$prCost1 = $row['cost1'];
$prCost2 = $row['cost2'];
$orderContent .= '
    <tr>
        <td>'.$prId.'</td>
        <td>'.$prDesc.'</td>
        <td>'.$prPack.'x'.$prSize.' '.$prMeasure.'</td>
        <td>R'.$prPrice1.'</td>
        <td>
            <form action="" method="post">
                <div>
                    <input type="hidden" name="id" value="'.$prId.'" />
                    <input type="submit" name="action" value="Order" />
                </div>
            </form>
        </td>           
   </tr>
';

if (isset($_GET['order']))
{
$order = array();
$total = 0;
foreach ($_SESSION['order'] as $id)
{
        foreach ($prId as $product)
        {
        if ($product == $id) 
            {
            $order[] = $product;
            $total += $prPrice1;
            break;
            }
        }

include($docRoot . '/orders/orders-finalize.php');
exit();

}
}
}}
include 'orders-layout.php';

?>

这是包含订单的最终确定:

<?php
ob_start();

<meta name="keywords" content="'.$keyWords.'" />
';

$belowMenu = '
<p>Orders Page</p>
';

$pageContent = '
<h2>Your order</h2>
';
if (count($order) > 0)
{
    $pageContent .= '
    <table>
        <thead>
            <tr>
                <th>Item Description</th>
                <th>Price</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <td>Total:</td>
                <td>R'.number_format($total, 2).'</td>
            </tr>
        </tfoot>
        <tbody>
';  
    foreach ($order as $item) 
{
    if ($item == $prId) 
    {
        $pageContent .= '
                <tr>
                    <td>'.$prDesc.'</td>
                    <td>
                        R'.number_format($prPrice1, 2).'
                    </td>
                </tr>
';      
    }
}
    $pageContent .= '
        </tbody>
        </table>
';

} else
{ 
$pageContent .= '
<p>Your cart is empty!</p>
';
}

$pageContent .= '
<form action="?" method="post">
    <p>
        <a href="?">Continue shopping</a>
        or
        <input type="submit" name="action" value="Clear order" />
    </p>
</form>
';


echo $head1 . $pageDetails . $head2 . $header . $menu . $belowMenu . $content . $pageContent . $footer . $pageScripts;
exit;
?>

这是订单布局包括:

<?php
ob_start();

$belowMenu = '
<p>Orders Page</p>
';

$pageContent = '
<h2>Place your order</h2>
<p>Your order contains '.count($_SESSION['order']).' items.</p>
<p><a href="?order">View your order</a></p>
<table border="1">
    <thead>
        <tr>
            <th>Stock Code</th>
            <th>Description</th>
            <th>Packsize</th>
            <th>Price</th>
            <th>Quantity</th>
        </tr>
    </thead>
    <tbody>
';

$pageContentEnd = '
    </tbody>
</table>
<br />
<p>All prices are inclusive of VAT</p>
';


echo $head1 . $pageDetails . $head2 . $header . $menu . $belowMenu . $content . $pageContent . $orderContent . $pageContentEnd . $footer . $pageScripts;
exit;
?>

这会生成一个页面,其中列出了每个结果。

如果用户点击“查看订单”,应该会跳转到一个页面,用户可以看到所有已订购的商品。

它的实际作用是清空会话并刷新页面。

如果有人能在这里发现我哪里出错了,如果您能提供一些意见,我们将不胜感激!

这是控制器所基于的代码:

<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
    '/includes/magicquotes.inc.php';

$items = array(
    array('id' => '1', 'desc' => 'Canadian-Australian Dictionary',
            'price' => 24.95),
    array('id' => '2', 'desc' => 'As-new parachute (never opened)',
            'price' => 1000),
    array('id' => '3', 'desc' => 'Songs of the Goldfish (2CD set)',
            'price' => 19.99),
    array('id' => '4', 'desc' => 'Simply JavaScript (SitePoint)',
            'price' => 39.95));

session_start();
if (!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}

if (isset($_POST['action']) and $_POST['action'] == 'Buy')
{
// Add item to the end of the $_SESSION['cart'] array
$_SESSION['cart'][] = $_POST['id'];
header('Location: .');
exit();
}

if (isset($_POST['action']) and $_POST['action'] == 'Empty cart')
{
// Empty the $_SESSION['cart'] array
unset($_SESSION['cart']);
header('Location: ?cart');
exit();
}

if (isset($_GET['cart']))
{
$cart = array();
$total = 0;
foreach ($_SESSION['cart'] as $id)
{
    foreach ($items as $product)
    {
        if ($product['id'] == $id)
        {
            $cart[] = $product;
            $total += $product['price'];
            break;
        }
    }
}

include 'cart.html.php';
exit();
}

include 'catalog.html.php';

?>

这是 cart.html.php 的代码:

<?php include_once $_SERVER['DOCUMENT_ROOT'] .
    '/includes/helpers.inc.php'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Shopping cart</title>
    <meta http-equiv="content-type"
            content="text/html; charset=utf-8" />
    <style type="text/css">
    table {
        border-collapse: collapse;
    }
    td, th {
        border: 1px solid black;
    }
    </style>
</head>
<body>
    <h1>Your Shopping Cart</h1>
    <?php if (count($cart) > 0): ?>
    <table>
        <thead>
            <tr>
                <th>Item Description</th>
                <th>Price</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <td>Total:</td>
                <td>$<?php echo number_format($total, 2); ?></td>
            </tr>
        </tfoot>
        <tbody>
            <?php foreach ($cart as $item): ?>
                <tr>
                    <td><?php htmlout($item['desc']); ?></td>
                    <td>
                        $<?php echo number_format($item['price'], 2); ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php else: ?>
    <p>Your cart is empty!</p>
    <?php endif; ?>
    <form action="?" method="post">
        <p>
            <a href="?">Continue shopping</a> or
            <input type="submit" name="action" value="Empty cart"/>
        </p>
    </form>
</body>

【问题讨论】:

  • 在 foreach 会话中包含 order finalize 是一个错字还是在您的实际代码中是这样的?
  • 像这样的相对重定向:header('Location: ?order'); 是不合法的,尽管它们可以在很多浏览器中使用。但尤其是这个甚至不是页面的可能不推荐。
  • 您需要在任何输出之前调用session_start - 也许将其移动到文件顶部(在任何包含之前)以确保?
  • @Dreaded 这不是错字,请参阅我对从站点手册中取出的原始脚本进行的编辑。
  • @Ariel 不合法是什么意思?

标签: php mysql session compare


【解决方案1】:

既然你说这不是粘贴到stackoverflow时引入的错字,请看这个:

foreach ($_SESSION['order'] as $id)
{
        foreach ($prId as $product)
        {
            if ($product == $id) 
            {
               $order[] = $product;
               $total += $prPrice1;
               break;
             }
        }

include($docRoot . '/orders/orders-finalize.php'); **//why this is included here? you are not yet looped to include all the orders from session inside order array**
exit();

}

看到我说为什么包含在这里的那一行吗?您尚未循环以将会话中的所有订单包含在订单数组中。您将该行放在循环遍历实际生成订单数组的会话的 foreach 中,但在包含的订单最终确定中,您尝试遍历未完成的订单

不确定这是否能解决您遇到的问题,但请尝试检查并告诉我们。

【讨论】:

  • 对于其他问题,尝试添加 session_write_close();在向会话添加订单之后的 header("location:.") 之前
  • 我的话!!!好吧,你是对的!但这现在将我带到显示“您的购物车为空”的页面。在原始页面上,我在订单中添加了一个项目,然后单击查看订单,但它似乎没有结束会话?
  • 你是否尝试添加 session_write_close(); ?请看我上面的评论。
  • 是的,我已经添加了这个。我认为可能没有任何东西被添加到 $order 数组,或者可能是 foreach 和 if 在 finalize 页面上,但我不太确定是什么。
  • 尝试使用例如 var_dump 调试代码,然后将 die() 放在可疑会话之后,然后确定哪个不能正常工作。有很多可能性。或者您可以创建一个函数将日志记录到文件中,并尝试在每个步骤中记录输出
猜你喜欢
  • 1970-01-01
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多