Создание корзины заказов - нажатие на кнопку «Просмотреть корзину» очищает сеанс и перезагружает страницу? - PullRequest
1 голос
/ 07 августа 2011

У меня проблемы с простым сценарием, который позволяет пользователю просматривать продукты, взятые из таблицы 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>

1 Ответ

1 голос
/ 07 августа 2011

Поскольку вы говорите, что это не опечатка, введенная при вставке в 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, который проходит через сеанс, который фактически генерирует массив ордеров, но во включенном порядке финализации вы пытаетесь перебрать незавершенные ордера

не уверен, решит ли это проблему, с которой вы столкнулись, но попробуйте проверить это и сообщите нам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...