0

我的问题是我有一个 cart_array 来存储添加到我的购物车中的产品。当我按下提交并通过第一个 php 块进行处理时,如果有足够的数据,它应该转到 unset($_SESSION['cart_array']); 部分并销毁cart_array,但是,它没有这样做,添加的项目仍然显示在我的cart.php 中。我试过 session_destroy 也没有运气。需要注意的是,它确实回显了 $success,这意味着代码应该通过该部分,但为什么它没有取消设置我的 cart_array?

<?php

if ($_POST['cartOutput']) {


$customer_name = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_name']);
$tel_num = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['tel_num']);
$customer_address = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_address']);
$customer_messages = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_messages']);
$error_status = false;

if (empty($customer_name)){
$error_customer_name ='<h4>Please Fill Your Name</h4>';
$error_status = true;
} 
if (empty($tel_num)){
$error_tel_num='<h4>Please Fill Your Contact Number</h4>';
$error_status = true;
} 
if (empty($customer_address)){
$error_customer_address='<h4>Please Fill Your Address</h4>';
$error_status = true;
}

if(!$error_status) {
include "storescripts/connect_to_mysqli.php";
$sql= 'INSERT INTO orders (customer_name,tel_num,customer_address,product_name, price, quantity, date_added,customer_messages) VALUES(?,?,?,?,?,?,NOW(),?)';      

$stmt = $myConnection->prepare($sql); 
$countArray = count($_POST["item_name"]);
for ($i = 0; $i < $countArray; $i++) {
$stmt->bind_param('sssssss', $customer_name,$tel_num,$customer_address, $_POST['item_name'][$i], $_POST['amount'][$i], $_POST['quantity'][$i],$customer_messages);
$stmt->execute();
}
 ; 

$to_address="someone@gmail.com";
$subject="Online Store Order Submission";

$cartTotal=$_POST['cartTotal'];

$message="Input from online order form.\n\n";
$message .="Name: ".$customer_name."\n";
$message .="Tel: ".$tel_num."\n";
$message .="Address: ".$customer_address."\n";
$message .="Messages: ".$customer_messages."\n";
$message .="Total:".$cartTotal."\n";

mail($to_address, $subject, $message);

$success= 'ORDER SUMITTED SUCCESSFULLY! Thank you and WELCOME to shop again!';

unset($_SESSION["cart_array"]);

}
}
?>

另一件需要注意的事情是,当我将表单操作发布到另一个文件时,比如说 order.php 并将上面的代码放入其中,它会取消会话,因为我将 POST 更改为 ISSET 并在取消设置之后放置 exit() ,当我尝试将 exit() 放入我的 cart.php 时,如果它成功提交,它就会变为空白。

任何帮助,将不胜感激

以下是HTML标签上方的所有PHP BLOCK供参考。

<?php

if ($_POST['cartOutput']) {


$customer_name = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_name']);
$tel_num = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['tel_num']);
$customer_address = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_address']);
$customer_messages = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_messages']);
$error_status = false;

if (empty($customer_name)){
$error_customer_name ='<h4>Please Fill Your Name</h4>';
$error_status = true;
} 
if (empty($tel_num)){
$error_tel_num='<h4>Please Fill Your Contact Number</h4>';
$error_status = true;
} 
if (empty($customer_address)){
$error_customer_address='<h4>Please Fill Your Address</h4>';
$error_status = true;
}

if(!$error_status) {
include "storescripts/connect_to_mysqli.php";
$sql= 'INSERT INTO orders (customer_name,tel_num,customer_address,product_name, price, quantity, date_added,customer_messages) VALUES(?,?,?,?,?,?,NOW(),?)';      

$stmt = $myConnection->prepare($sql); 
$countArray = count($_POST["item_name"]);
for ($i = 0; $i < $countArray; $i++) {
$stmt->bind_param('sssssss', $customer_name,$tel_num,$customer_address, $_POST['item_name'][$i], $_POST['amount'][$i], $_POST['quantity'][$i],$customer_messages);
$stmt->execute();
}
 ; 

$to_address="someone@gmail.com";
$subject="Online Store Order Submission";

$cartTotal=$_POST['cartTotal'];

$message="Input from online order form.\n\n";
$message .="Name: ".$customer_name."\n";
$message .="Tel: ".$tel_num."\n";
$message .="Address: ".$customer_address."\n";
$message .="Messages: ".$customer_messages."\n";
$message .="Total:".$cartTotal."\n";

mail($to_address, $subject, $message);

$success= 'ORDER SUMITTED SUCCESSFULLY! Thank you and WELCOME to shop again!';

unset($_SESSION["cart_array"]);

}
}
?>

<?php
    session_start();
    /* Created by Adam Khoury @ www.developphp.com */
    // Connect to the MySQL database  
    include "storescripts/connect_to_mysqli.php";


    // Query the module data for display ---------------------------------------------------------------------------------------------------------------
    $sqlCommand = "SELECT modulebody FROM modules WHERE showing='1' AND name='footer' LIMIT 1";
    $query = mysqli_query($myConnection, $sqlCommand) or die(mysqli_error());
    while ($row = mysqli_fetch_array($query)) {
        $footer = $row["modulebody"];
    }
    mysqli_free_result($query);
    //---------------------------------------------------------------------------------------------------------------------------------------------------------------
    // Query the module data for display ---------------------------------------------------------------------------------------------------------------
    $sqlCommand = "SELECT modulebody FROM modules WHERE showing='1' AND name='custom1' LIMIT 1";
    $query = mysqli_query($myConnection, $sqlCommand) or die(mysqli_error());
    while ($row = mysqli_fetch_array($query)) {
        $custom1 = $row["modulebody"];
    }
    mysqli_free_result($query);
    //---------------------------------------------------------------------------------------------------------------------------------------------------------------
    // Build Main Navigation menu and gather page data here -----------------------------------------------------------------------------


    $sqlCommand = "SELECT id, linklabel FROM pages WHERE showing='1' ORDER BY id DESC";
    $query = mysqli_query($myConnection, $sqlCommand) or die(mysqli_error());

    $menuDisplay = '';
    while ($row = mysqli_fetch_array($query)) {
        $pid = $row["id"];
        $linklabel = $row["linklabel"];
        $menuDisplay .= '<a href="index.php?pid=' . $pid . '">' .
                $linklabel . '</a><br />';
    }
    mysqli_free_result($query);
    //---------------------------------------------------------------------------------------------------------------------------------------------------------------
    //mysqli_close($myConnection); 
    // This file is www.developphp.com curriculum material
    // Written by Adam Khoury January 01, 2011
    // http://www.youtube.com/view_play_list?p=442E340A42191003
    // Script Error Reporting
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //       Section 1 (if user attempts to add something to the cart from the product page)
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    if (isset($_POST['pid'])) {
        $pid = $_POST['pid'];
        $wasFound = false;
        $i = 0;
        // If the cart session variable is not set or cart array is empty
        if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
            // RUN IF THE CART IS EMPTY OR NOT SET
            $_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1));
        } else {
            // RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
            foreach ($_SESSION["cart_array"] as $each_item) {
                $i++;
                while (list($key, $value) = each($each_item)) {
                    if ($key == "item_id" && $value == $pid) {
                        // That item is in cart already so let's adjust its quantity using array_splice()
                        array_splice($_SESSION["cart_array"], $i - 1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
                        $wasFound = true;
                    } // close if condition
                } // close while loop
            } // close foreach loop
            if ($wasFound == false) {
                array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
            }
        }
        header("location: cart.php");
        exit();
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //       Section 2 (if user chooses to empty their shopping cart)
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    if (isset($_GET['cmd']) && $_GET['cmd'] === 'emptycart') {
        unset($_SESSION["cart_array"]);
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //       Section 3 (if user chooses to adjust item quantity)
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") {
        // execute some code
        $item_to_adjust = $_POST['item_to_adjust'];
        $quantity = $_POST['quantity'];
        $quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter everything but numbers
        if ($quantity >= 100) {
            $quantity = 99;
        }
        if ($quantity < 1) {
            $quantity = 1;
        }
        if (empty($quantity)) {
            $quantity = 1;
        }
        $i = 0;
        foreach ($_SESSION["cart_array"] as $each_item) {
            $i++;
            while (list($key, $value) = each($each_item)) {
                if ($key == "item_id" && $value == $item_to_adjust) {
                    // That item is in cart already so let's adjust its quantity using array_splice()
                    array_splice($_SESSION["cart_array"], $i - 1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
                } // close if condition
            } // close while loop
        } // close foreach loop
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //       Section 4 (if user wants to remove an item from cart)
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] !== '') {
        // Access the array and run code to remove that array index
        $key_to_remove = $_POST['index_to_remove'];
        if (count($_SESSION["cart_array"]) <= 1) {
            unset($_SESSION["cart_array"]);
        } else {
            unset($_SESSION["cart_array"][$key_to_remove]);
            sort($_SESSION["cart_array"]);
        }
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //       Section 5  (render the cart for the user to view on the page)
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    $cartOutput = "";
    $cartTotal = "";
    $pp_checkout_btn = '';
    $product_id_array = '';

    if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
        $cartOutput = "<h3 align='center'>Your shopping cart is empty</h3>";
    } else {
        // Start PayPal Checkout Button

        $pp_checkout_btn .= '<form action=" " method="post">
    <input type="hidden" name="cartOutput" value = "$cartOutput">';

        // Start the For Each loop
        $i = 0;
        foreach ($_SESSION["cart_array"] as $each_item) {
            $item_id = $each_item['item_id'];
            $sqlCommand = "SELECT * FROM products WHERE id='$item_id' LIMIT 1";
            $sql = mysqli_query($myConnection, $sqlCommand);
            while ($row = mysqli_fetch_array($sql)) {
                $product_name = $row["product_name"];
                $price = $row["price"];
                $details = $row["details"];
            }
            $pricetotal = $price * $each_item['quantity'];
            $cartTotal = $pricetotal + $cartTotal;
            setlocale(LC_MONETARY, "ms_MY");
            $pricetotal = money_format("%10.2n", $pricetotal);
    // Dynamic Checkout Btn Assembly

            $pp_checkout_btn .= '<input type="hidden" name="item_name[]" value="' . $product_name . '">
    <input type="hidden" name="amount[]" value="' . $price . '">
    <input type="hidden" name="quantity[]" value="' . $each_item['quantity'] . '">  ';
            // Create the product array variable
            $product_id_array .= "$item_id-" . $each_item['quantity'] . ",";
            // Dynamic table row assembly
            $cartOutput .= "<tr>";
            $cartOutput .= '<td><center><a href="product.php?id=' . $item_id . '">' . $product_name . '</a><br /><img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_name . '" width="40" height="52" border="0" /></center></td>';
            $cartOutput .= '<td>' . $details . '</td>';
            $cartOutput .= '<td><center>RM' . $price . '</center></td>';
            $cartOutput .= '<td><center><form action="cart.php" method="post">
            <input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" />
            <input name="adjustBtn' . $item_id . '" type="submit" value="change" />
            <input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
            </form></center></td>';
            //$cartOutput .= '<td><center>' . $each_item['quantity'] . '</center></td>';
            $cartOutput .= '<td><center>' . $pricetotal . '</center></td>';
            $cartOutput .= '<td><center><form action="cart.php" method="post"><input name="deleteBtn' . $item_id . '" type="submit" value="X" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></center></td>';
            $cartOutput .= '</tr>';
            $i++;
        }
        setlocale(LC_MONETARY, "ms_MY");
        $cartTotal = money_format("%10.2n", $cartTotal);
        $cartTotal = "<div style='font-size:18px; margin-top:12px;' align='right'>Cart Total : " . $cartTotal . " MYR</div>";
        // Finish the Paypal Checkout Btn
         $pp_checkout_btn .= '<input type="hidden" name="custom" value="' . $product_id_array . '">
<div id="table">
    Name: <input type="text" name="customer_name">
    <br/>
    Tel: <input type="text" name="tel_num">
    <br/>
    Address: <input type="text" name="customer_address">
    <br/>
    Messages: <textarea name="customer_messages">

</textarea>

    <input type="hidden" name="cartTotal" value="' . $cartTotal . '">

        <input type="submit" value="Submit">
</div>
        </form>';


    }
    ?>  
4

1 回答 1

1

如果你想操纵会话,unset($_SESSION["cart_array"]);你必须有一个会话来操纵。

因此,如果您session_start();在第一段代码的顶部添加 a ,它可能会正确取消设置

如:-

<?php

session_start();

if ($_POST['cartOutput']) {

....
于 2013-08-13T12:57:03.313 回答