我是php的新手,购物车文件名为wholesalecart.php

每当我完成订单并继续购物后,将新产品添加到购物车中,以前的产品仍在购物车中。

因此,我认为购买后可能需要在数据库中清空购物车,以便下次下次继续购物时,它不会保留数据库中的旧商品。

wholesalecart.php文件代码如下:
    

require_once("../login/protect.php");

 //required for db connection
require_once '../includes/conn.php';



function updateDbCart(){
$userId = $_SESSION['id'];

//create our json cart if it exists ready to put in db
if (!empty($_SESSION['wholesalecart'])){
    $jsonCart = json_encode($_SESSION['wholesalecart']);
} else {
    $jsonCart = '';
}

//see if user already has a record in db for us else add it
$query = "SELECT count(*) as found FROM user_carts WHERE user_id='$userId'";
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
if($data['found']) {
    $query = "UPDATE user_carts SET cart='$jsonCart' WHERE user_id='$userId'";
    $result = mysql_query($query);
} else {
    $query = "INSERT INTO user_carts (user_id, cart) VALUES ('$userId', '$jsonCart')";
    $result = mysql_query($query);
}
}


if(!empty($_POST['sendwholesale']))
{
$i=0;
foreach ($_POST as $p => $q)
{
    $i++;
    if(ctype_digit($_POST['qty'.$i]))
    {
        $_SESSION['wholesalecart'][$_POST['prodid'.$i]] = $_POST['qty'.$i];
    }
}
updateDbCart();
}
elseif (isset($_POST['update']))
{
$prod = $_POST['prodid'];
$qty = (ctype_digit($_POST['qty']) ? $_POST['qty'] : 1);
$_SESSION['wholesalecart'][$prod] = $qty;
updateDbCart();
}
elseif (isset($_POST['remove']))
{
$prod = $_POST['prodid'];
unset($_SESSION['wholesalecart'][$prod]);
updateDbCart();
}
elseif (isset($_POST['empty']))
{
unset($_SESSION['wholesalecart']);
updateDbCart();
}



$_SESSION['wholesaletotalItems'] = 0;
if (!empty($_SESSION['wholesalecart']))
{
foreach ($_SESSION['wholesalecart'] as $p => $q)
{
    $_SESSION['wholesaletotalItems'] += $q;
}
}


$_SESSION['wholesaletotal'] = 0;
$cartTotal = 0;


//get the cart from db
$userId = $_SESSION['id'];
$query = "SELECT cart as cartDataFromDb FROM user_carts WHERE user_id='$userId'";
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
$_SESSION['wholesalecart'] = json_decode($data['cartDataFromDb'], true);



if (!empty($_SESSION['wholesalecart']))
    {
    $displayContent = '
        <table id="shopCart">
            <tr class="tableHead">
                <td>Product Code</td>
                <td>Product Name</td>
                <td class="center small">Price</td>
                <td class="center qtysmall">Qty</td>
                <td class="center small">Subtotal</td>
                <td class="center small"></td>
            </tr>
    ';

    $i=0;
    foreach ($_SESSION['wholesalecart'] as $p => $q)
    {

        $query = "SELECT * FROM products WHERE prodid='$p'";
        $result = mysql_query($query);

        while ($data = mysql_fetch_array($result))
        {
            $i++;

            $price = sprintf('%.2f',$data['wholesaleprice']);
            $subTotal = ($price * $q);

            $displayContent .= '
            <tr class="cartRow">
                <td>'.$data['prodid'].'</a></td>
                <td>'.$data['prodname'].'</td>
                <td class="center">$'.$price.'</td>
                <td class="center">
                <form action="wholesalecart.php" method="post">
                    <input type="hidden" name="prodid" value="'.$data['prodid'].'" />
                    <input type="text" class="qty" name="qty" size="3" maxlength="3" value="'.$q.'" />
                    <input type="submit" class="update" name="update" value="Update" />
                </form>
                </td>
                <td class="center">$'.$subTotal.'</td>
                <td class="center">
                <form action="wholesalecart.php" method="post">
                    <input type="hidden" name="prodid" value="'.$data['prodid'].'" />
                    <input type="submit" class="remove" name="remove" value="Remove" />
                </form>
                </td>
            </tr>';


            $checkout .= '
            <input type="hidden" value="'.$data['prodname'].' - '.$p.'" name="item_name_'.$i.'"/>
            <input type="hidden" value="'.$q.'" name="quantity_'.$i.'"/>
            <input type="hidden" value="'.$price.'" name="amount_'.$i.'"/>
            <input type="hidden" value="'.$i.'" name="count"/>
            ';

            $_SESSION['wholesaletotal'] += $subTotal;
            $cartTotal += $subTotal;
        } //end while
    } //end foreach
    $i++;

    //add button to email the cart if logged in
    if(isset($_SESSION['username']))
    {
        $emailIt = '
            <tr class="cartRow">
                <form action="wholesalemailcart.php" method="post">
                <td colspan="6">Additional comments:<br /><textarea style="width:450px;height:80px;" name="cartMessage">'.$_SESSION['cartMessage'].'</textarea></td>
            </tr>
            <tr class="actionsRow">
                <td colspan="4"></td>
                <td colspan="2" class="left">
                        <input type="submit" class="checkout" name="mail" value="Continue With Order" />
                    </form>
                </td>
            </tr>
        ';
    }

    $displayContent .= '
            <tr class="freightRow">
                <td colspan="2" class="center">
                    <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
                    '.$checkout.'

                        <input type="hidden" value="Shipping" name="item_name_'.$i.'"/>
                        <input type="hidden" value="1" name="quantity_'.$i.'"/>
                        <input type="hidden" value="'.$i.'" name="count"/>
                </td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <tr class="totalsRow">
                <td></td>
                <td></td>
                <td class="subtotal">Subtotal</td>
                <td class="subtotal">'.$_SESSION['wholesaletotalItems'].'</td>
                <td class="subtotal">'.sprintf('%.2f',$_SESSION['wholesaletotal']).'</td>
                <td></td>
            </tr>
            <tr class="actionsRow">
                <td></td>
                <td></td>
                <td colspan="2" class="center">
                        <input type="hidden" value="_cart" name="cmd"/>
                        <input type="hidden" value="1" name="upload"/>
                        <input type="hidden" value="[email protected]" name="business"/>
                        <input type="hidden" value="NZD" name="currency_code"/>
                        <!-- <input type="submit" class="checkout" name="Action" value="Checkout" /> -->
                    </form>
                </td>
                <td colspan="2" class="left">
                    <!-- old $emailIt -->
                </td>
                '.$emailIt.'
            </tr>
        </table>


    ';
}
else
{
$displayContent = '<p class="center">Sorry you have no items in your Shopping cart</p>
<p class="center"><a href="../shopping/index.php">Continue Shopping?</a></p>';
}




?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- InstanceBegin template="/Templates/template.dwt" codeOutsideHTMLIsLocked="false" -->

<head>



    <link href="../css/hbcl-styles.css" rel="stylesheet" type="text/css" media="screen" />
    <link href="../css/menu.css" rel="stylesheet" type="text/css" media="screen" />
    <link href="../css/shop.css" rel="stylesheet" type="text/css" media="screen" />
    <link href="../css/map-styles.css" rel="stylesheet" type="text/css" media="screen" />
</head>

<body>

    <div id="wrap">
        <a name="top"></a>

        <div id="header"></div>

        <div id="main">
            <div id="left-content">
                <div id="left-menu">
                    <?php include('../includes/menu.php'); ?>
                </div>
                <?php include('../includes/left-sidebar.php'); ?>
            </div>
            <!-- InstanceBeginEditable name="content" -->
            <div id="middle-content">
                <h1>Wholesale Shopping Cart</h1>
                <h3>Continue Shopping    </h3>
                <p>Select and add more products from the left hand dealer product menu to your shopping cart.
                    <br />
                    <br />
                </p>
                <h3>Shopping Cart Contents</h3>
                <p>At any time you can select the <strong>Cart</strong> button at the bottom of the left hand menu to check the contents of your shopping cart.
                    <br />
                    <br />
                </p>
                <h3>Continue With Order</h3>
                <p>Once your cart is complete, select <strong>Continue With Order</strong>.</p>
                <p>&nbsp;</p>
                <?php echo $displayContent ?>
            </div>
            <!-- InstanceEndEditable -->
            <div id="right-content">
                <?php include('../includes/right-sidebar.php'); ?>
            </div>

            <?php include('../includes/footer.php'); ?>
        </div>

    </div>

</body>
<!-- InstanceEnd -->

</html>


表单标签中的Continue With Order按钮,链接到wholesalemailcart.php

<?php
session_start();

require_once("../login/protect.php");

//required for db connection
require_once '../includes/conn.php';
require_once '../classes/class.phpmailer.php';

if(isset($_POST['mail'])){
$_SESSION['cartMessage'] = $_POST['cartMessage'];
}

if (!empty($_SESSION['wholesalecart']))
{
    $i=0;
    $cartTotal=0;
    foreach ($_SESSION['wholesalecart'] as $p => $q)
    {

        $query = "SELECT * FROM products WHERE prodid='$p'";
        $result = mysql_query($query);


        while ($data = mysql_fetch_array($result))
        {
            $i++;
            $price = $data['wholesaleprice'];
            $subTotal = ($price * $q);

            $mailContent .= '
            <tr class="cartRow">
                <td>'.$data['prodname'].'</td>
                <td>'.$data['prodid'].'</td>
                <td class="center">$'.$price.'</td>
                <td class="center">'.$q.'</td>
                <td class="center">$'.sprintf('%.2f',$subTotal).'</td>
            </tr>
            ';

            $cartTotal += $subTotal;

        } //end while
    } //end foreach

    $body = '<br />
    <table id="shopCart">
            <tr class="tableHead">
                <td>Product Name</td>
                <td>Code</td>
                <td class="center">Price Per Item</td>
                <td class="center qtysmall">Qty</td>
                <td class="center small">Subtotal</td>
            </tr>
        '.$mailContent.'
            <tr>
                <td></td>
                <td></td>
                <td class="center"><strong>Subtotal</strong></td>
                <td class="center">'.$_SESSION['totalItems'].'</td>
                <td class="center">$'.sprintf('%.2f',$cartTotal).'</td>
            </tr>
            <tr class="totalsRow">
                <td></td>
                <td></td>
                <td class="subtotal">Subtotal</td>
                <td class="subtotal">'.$_SESSION['wholesaletotalItems'].'</td>
                <td class="subtotal">'.sprintf('%.2f',$_SESSION['wholesaletotal']).'</td>
                <td></td>
            </tr>
            <tr>
                <td colspan="5" class="cartRow">Additional message: <strong>'.$_SESSION['cartMessage'].'</strong></td>
            </tr>
        </table>

    ';

}

if(!isset($_POST['confirmSend']))
{
$id = $_SESSION['id'];
$username = $_SESSION['username'];
$query = "SELECT * FROM logins WHERE id='$id' AND username='$username'";
$result = mysql_query($query);
while($data = mysql_fetch_array($result))
{
    $name = $data['name'];
    $email = $data['email'];
    $address = $data['address'];
    $address1 = $data['address1'];
    $address2 = $data['address2'];
    $address3 = $data['address3'];
    $city = $data['city'];
}


$displayContent = '
<h1>Shopping Cart Completion</h1>
<p><strong>Your details.</strong></p><br/>
<form action="'.$_SERVER['SCRIPT_NAME'].'" method="post">
<table>
    <tr>
        <td class="mailform" width="150">Company Name:</td><td>    <p>'.$name.'</p></td>
    </tr>
    <tr>
        <td class="mailform">Email Address:</td><td><p>'.$email.'</p></td>
    </tr>
    <tr>
        <td class="mailform">Address:</td><td><p>'.$address1.'</p></td>
    </tr>
    <tr>
        <td class="mailform"></td><td><p>'.$address2.'</p></td>
    </tr>
    <tr>
        <td class="mailform"></td><td><p>'.$address3.'</p></td>
    </tr>
    <tr>
        <td class="mailform"></td><td><p>'.$city.'</p></td>
    </tr>
    <tr>
        <td class="mailform"></td><td><p>'.$address.'</p></td>
    </tr>
</table>


<p><strong>Your Order will be sent Hauraki Brewing containing the following selections.</strong></p>

'.$body.'
<br />
    <p>Please select <strong>Send Order</strong> to complete your wholesale order.</p><br/>

        <input type="submit" name="confirmSend" value="Send Order">
    </form>
';
}
elseif(!empty($_SESSION['wholesalecart']) && (isset($_POST['confirmSend']) || isset($_POST['ReconfirmSend']) ))
{
$id = $_SESSION['id'];
$username = $_SESSION['username'];
$query = "SELECT * FROM logins WHERE id='$id' AND username='$username'";
$result = mysql_query($query);
while($data = mysql_fetch_array($result))
{
    $name = $data['name'];
    $email = $data['email'];
    $address = $data['address'];
    $address1 = $data['address1'];
    $address2 = $data['address2'];
    $address3 = $data['address3'];
    $city = $data['city'];
}

if(isset($_POST['ReconfirmSend']))
{
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $location = $_POST['location'];
    $address = $data['address'];
}

if(strlen($name) > 2 && strlen($email) > 2)
{
    $mail = new PHPMailer();

    $mail->From = $email;
    $mail->FromName = $name;
    $mail->AddAddress("XXXX");
    $mail->AddReplyTo($email, $name);

    $mail->WordWrap = 50;
    //$mail->AddAttachment("/tmp/image.jpg", "new.jpg");    // optional attachemnt and name
    $mail->IsHTML(true);

    $mail->Subject = $name.' - Hauraki Brewing Wholesale Order';
    $mail->Body    = '
        <br>
        Order From: '.$name.' <br><br/>

        Email: '.$email.'<br>

        Address: '.$address1.'<br>
    '.$address2.'<br>
    '.$address3.'<br>
    '.$city.'<br>
    '.$address.'
        <br><br>

        <br><br>

        '.$body.'

        <br>
        ';
    //$mail->AltBody = "$message";

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

        //send second email
    $mail2 = new PHPMailer();

    $mail2->From = $email;
    $mail2->FromName = $name;
    $mail2->AddAddress($email);
    $mail2->AddReplyTo($email, $name);

    $mail2->WordWrap = 50;
    //$mail->AddAttachment("/tmp/image.jpg", "new.jpg");    // optional attachemnt and name
    $mail2->IsHTML(true);

    $mail2->Subject = $name.' - Hauraki Brewing Order Confirmation';
    $mail2->Body    = '
        <br>
        Thank you for your order.<br/><br/>A copy of the order you placed is included below. Please phone or email us immediately if you see any discrepancies in what you ordered.<br/>
        '.$body.'

        <br>
        ';
    //$mail->AltBody = "$message";

    if(!$mail2->Send())
    {
       echo "second Message could not be sent. <p>";
       echo "Mailer Error: " . $mail2->ErrorInfo;
       exit;
    }



    /**
     *
     * For debugging send a third email to david
     *
     */



    /*
     * End debug section
     */




    //header("Location: order-form.php?success=y");
    //exit();

    $displayContent .= '
        <h1>Wholesale Order Completed</h1>

        <p>Your wholesale order has been sent successfully. You should receive a confirmation email that your order has been sent.<br/><br/>
        Thank you for your order, we appreciate your business. <br/><br/>
        Continue shopping and place another order or <a href="../login/logout.php">logout</a>.
        </p>
    ';
}
else
{
    $displayContent = '
    <p class="error">Invalid Fields</p>

    <p><strong>Please enter your details to continue.</strong></p><br/>
    <form action="'.$_SERVER['SCRIPT_NAME'].'" method="post">
    <table>
    <tr>
    <td class="mailform" width="150">Company Name:</td><td><input type="text" name="name" value="" maxlength="100" size="40"/></td>
    </tr>
    <td class="mailform">Phone:</td><td><input type="text" name="phone" value="" maxlength="100" size="40"/></td>
    </tr>
    <td class="mailform">Email Address:</td><td><input type="text" name="email" value=""maxlength="100" size="40" /></td>
    </tr>
    <td class="mailform">Location (Town/City):</td><td><input type="text" name="location" value="" maxlength="100" size="40" /></td>
    </tr>
    </table>


    <p><strong>Your email will list these products.</strong></p>

    '.$body.'

    <p>This will email your Order Enquiry to Hauraki Brewing, click <strong>Send Enquiry</strong> to continue.</p><br/>

        <input type="submit" name="ReconfirmSend" value="Confirm and send">
    </form>
';
}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



    

<body>

<div id="wrap"><a name="top"></a>

<div id="header"></div>

<div id="main">
<div id="left-content">
<div id="left-menu">
<?php include('../includes/menu.php'); ?>
</div>
<?php include('../includes/left-sidebar.php'); ?>
</div>
<!-- InstanceBeginEditable name="content" -->
<div id="middle-content">
<?php echo $displayContent ?>
 </div>
<!-- InstanceEndEditable -->
<div id="right-content">
<?php include('../includes/right-sidebar.php'); ?>
</div>

<?php include('../includes/footer.php'); ?>
</div>

</div>

</body>
<!-- InstanceEnd --></html>

最佳答案

欢迎来到有趣而有时令人沮丧的PHP编程世界!!

如果我正确地滚动浏览,您的购物车会保存在session变量中,这是很常见的...我也将它们用于购物车。您提到了数据库,但是没有看到购物车引用的那个数据库...除非我错过了它。 SESSION变量会“保留”一段可变的时间,具体取决于许多不同的设置(PHPINFO,超时等),或者除非您亲自使用unset清除它们。

如果您所描述的是正确的,听起来就像您碰到了头上的钉子,需要在订单之间将购物车清理干净。

我确实注意到一些看起来像是出于该目的而编写的代码,但是我可能错了……

elseif (isset($_POST['empty']))
{
    unset($_SESSION['wholesalecart']);
    updateDbCart();
}


但是通过查看您提供的代码,我看不到在任何地方都可以调用它。您只是错过了清理购物车的电话吗?

关于php - PHP-购买后从数据库中清除购物车,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34080241/

10-13 03:33