PHP / AJAX购物车无法正常工作

时间:2014-05-20 08:13:37

标签: php sql ajax

我在构建购物车时遇到了一些问题。

我无法为店铺中的每件商品设置不同的数量。应该从输入字段中获取数量,此时工作正常。但是,如果您将项目1的数量设置为3,项目2的数量设置为5,则每个项目的数量将为5(最后添加的数量)。

此外,当您尝试删除其中一个项目时,现在每个项目的数量将设置为零。就像是,每个项目的数量都没有存储,我不知道为什么会发生这种情况。

我正在使用的购物车是PHP / SQL和AJAX。

到目前为止,这是我的代码:

PHP:

<?php

// This doument contains the AJAX generated for the building-cart
/////////////////////////////////////////////////////////////////

// Clear Cache and include config.php
include("includes/config.php");
// Start Session
session_start();

?>
<?php

$product_id = $_GET['id']; //the product id from the URL 
$action = $_GET['action']; //the action from the URL
$quantitys = $_GET['qun']; //the action from the URL 

// if there is an product_id and that product_id doesn't exist display an error message
if($product_id && !productExists($product_id)) {
    die("Error. Product Doesn't Exist");
}

// decide what to do 
switch($action) {

    case "add":

    //add one to the quantity of the product with id $product_id 
    if($_SESSION['cart'][$product_id] < 1) { $_SESSION['cart'][$product_id]++; }

    break;

    case "remove":
        $_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id 
        if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items. 
    break;

    case "empty":
        unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart. 
    break;

}
?>
<?php 

//if the cart isn't empty show the cart
if($_SESSION['cart']) {

    echo '<ul id="cart-items">'."\n";

    //iterate through the cart, the $product_id is the key and $quantity is the value
    foreach($_SESSION['cart'] as $product_id => $quantityt) { 

        //get the name, description and price from the database - this will depend on your database implementation.
        //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
         $result = mysql_query("SELECT * FROM single_partners WHERE single_id = $product_id");

        //Only display the row if there is a product (though there should always be as we have already checked)
        if(mysql_num_rows($result) > 0) {

            if($test = mysql_fetch_array($result)) {
                $partner_id = $test['partner_id'];
                $partner_price = $test['price'];
            }   

            // Get partner name
            $get_partner_name = mysql_query("SELECT * FROM partners WHERE partner_id='$partner_id'");
            if($partner_name = mysql_fetch_array($get_partner_name)) {

                $name = $partner_name['name'];
                $logo = $partner_name['logo'];
                $type = $partner_name['type'];
                $logo_dir = "media/partners/build/color/";

                $line_cost = $partner_price * $quantitys; //work out the line cost
                $total = $total + $line_cost; //add to the total cost
            }

            echo '<li>'."\n";
            echo '<div class="logo" style="background-image: url('.$logo_dir.$logo.')">'."\n";
            echo '</div>'."\n";
            echo '<div class="details">'."\n";
            echo '<span class="name">'.$name.'</span>'."\n";
            echo '<span class="details">details</span>'."\n";
            echo '</div>'."\n";
            echo '<div class="price"><input name="qun" type="hidden" value="'.$quantitys.'" /><input name="partner" type="hidden" value="'.$product_id.'" /><span class="remove-button"></span>'."\n";
            echo '<span class="price">'.number_format((float)$line_cost, 2, ',', '').'</span>'."\n";
            echo '</div>'."\n";
            echo '</li>'."\n";
        }
    }
    echo '<div class="footer">'."\n";
    echo '<span class="empty-button">Empty</span>'."\n";
    echo '<span class="total-price">'.number_format((float)$total, 2, ',', '').'</span>'."\n";
    echo '</div>'."\n";
    echo '</ul>'."\n";



}else{
//otherwise tell the user they have no items in their cart
    //echo "You have no items in your shopping cart.";

}

//function to check if a product exists
function productExists($product_id) {
    //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
    $sql = mysql_query("SELECT * FROM single_partners WHERE single_id = $product_id");

    return mysql_num_rows($sql) > 0;
}
?>

AJAX致电:

// Load building cart, when adding items
$(document).on('click', 'input[type=button].add-button', function() {

    // AJAX - Define data to send
    var actiontype = "add";
        productid = $('input[name="address"]').val();
        quantity = $('input[name="qun"]').val();
    var data = "action="+ actiontype + "&id="+ productid + "&quantity="+ quantity;
    $.ajax({
        url: 'buildingcart.php',
        data: data,
        success:function(result) {  
            // Show result
            $('#building-cart .content').html(result);
        }
    });
});

// Load building cart, when adding items
$(document).on('click', '.remove-button', function() {

    // AJAX - Define data to send
    var actiontype = "remove";
        productid = $(this).parent().find('input[name="partner"]').val();

    var data = "action="+ actiontype + "&id="+ productid;
    $.ajax({
        url: 'buildingcart.php',
        data: data,
        success:function(result) {  
            // Show result
            $('#building-cart .content').html(result);
        }
    });
});

// Load building cart, when adding items
$(document).on('click', '.empty-button', function() {

    // AJAX - Define data to send
    var actiontype = "empty";

    var data = "action="+ actiontype;
    $.ajax({
        url: 'buildingcart.php',
        data: data,
        success:function(result) {  
            // Show result
            $('#building-cart .content').html(result);
        }
    });
});

我尝试过更改

foreach($_SESSION['cart'] as $product_id => $quantity)

foreach($_SESSION['cart'] as $product_id)

没有运气。

我也希望能够为每个项目设置不同的大小,但同样的事情发生在这里。它总是需要最后添加的项目的数量/大小,并将其更新为其他项目,这不是预期的。

对不起长码。希望有人可以帮助我: - )

0 个答案:

没有答案
相关问题