Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AJAX/PHP购物车,工作不正常_Php_Jquery_Ajax - Fatal编程技术网

AJAX/PHP购物车,工作不正常

AJAX/PHP购物车,工作不正常,php,jquery,ajax,Php,Jquery,Ajax,我在建造购物车方面遇到了一些问题 我想直接在输入中更改数量,而不是多次单击add按钮来更改数量。它工作得很好,但是当您删除购物车中的一个项目时,所有其他项目的价格都将设置为零,我不知道为什么会发生这种情况 我使用的购物车是PHP/SQL和AJAX 这是我目前的代码: PHP: <?php // This document contains the AJAX generated for the building-cart //////////////////////////////////

我在建造购物车方面遇到了一些问题

我想直接在输入中更改数量,而不是多次单击add按钮来更改数量。它工作得很好,但是当您删除购物车中的一个项目时,所有其他项目的价格都将设置为零,我不知道为什么会发生这种情况

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

这是我目前的代码:

PHP:

<?php

// This document 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
$quantity = $_GET['quantity']; //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 => $quantity) { 

        //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'];

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

            // 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/";

            }

            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">Detaljer</span>'."\n";
            echo '</div>'."\n";
            echo '<div class="price"><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">Tøm</span>'."\n";
    echo '<span class="total-price">'.number_format((float)$total, 2, ',', '').'</span>'."\n";
    echo '</div>'."\n";
    //show the total
//    echo "<tr>";
//    echo "<td colspan=\"2\" align=\"right\">Total</td>";
//    echo "<td align=\"right\">$total</td>";
//    echo "</tr>";
//
//    //show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation
//    echo "<tr>";
//    echo "<td colspan=\"3\" align=\"right\"><a href=\"$_SERVER[PHP_SELF]?action=empty\" onclick=\"return confirm('Are you sure?');\">Empty Cart</a></td>";
//    echo "</tr>"; 
    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;
}
?>
// 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($\u SESSION['cart']作为$product\u id=>$quantity)


运气不好。

你忘了在这一行上有一个$符号

$line_成本=$partner_价格*数量//计算线路成本

应该是

$line\u成本=$partner\u价格*$数量//计算线路成本

编辑: 此外,您可能希望优化代码,以便只选择一个sql,如下所示:

//if the cart isn't empty show the cart
if($_SESSION['cart']) {
    echo '<ul id="cart-items">'."\n";

    $productIds = implode(",", array_keys($_SESSION['cart']));

    $sql = "
        SELECT
            single_partners.single_id AS product_id,
            single_partners.partner_id,
            single_partners.price,
            partners.name,
            partners.logo,
            partners.type

        FROM single_partners
        INNER JOIN partners
            ON partners.partner_id = single_partners.partner_id
        WHERE single_id IN ({$productIds})
    ";
    $result = mysql_query($sql);

    $logo_dir = "media/partners/build/color/";
    if(mysql_num_rows($result) > 0) {
        while($row = mysql_fetch_array($result)) {
            $product_id = $row['product_id'];
            $partner_id = $row['partner_id'];
            $partner_price = $row['price'];
            $name = $row['name'];   
            $logo = $row['logo'];
            $type = $row['type'];
            $quantity = $_SESSION['cart'][$product_id];

            $line_cost = $partner_price * $quantity; //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">Detaljer</span>'."\n";
            echo '</div>'."\n";
            echo '<div class="price"><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 '</ul>'."\n";
}
else{
    //otherwise tell the user they have no items in their cart
    //echo "You have no items in your shopping cart.";
}   
//如果购物车不是空的,则显示购物车
如果($\u会话['cart']){
echo'
    。“\n”; $productIds=内爆(“,”,数组_键($_会话['cart']); $sql=” 挑选 single_partners.single_id作为产品id, 单一合伙人。合伙人id, 单一价格, 合作伙伴名称, partners.logo, 伙伴类型 来自单一合伙人 内部联接伙伴 ON partners.partners\u id=单个\u partners.partner\u id 其中({$productIds})中的单个_id "; $result=mysql\u查询($sql); $logo_dir=“media/partners/build/color/”; 如果(mysql_num_rows($result)>0){ while($row=mysql\u fetch\u数组($result)){ $product_id=$row['product_id']; $partner_id=$row['partner_id']; $partner_price=$row['price']; $name=$row['name']; $logo=$row['logo']; $type=$row['type']; $quantity=$\会话['cart'][$product\u id]; $line\u cost=$partner\u price*$quantity;//计算线路成本 $total=$total+$line\U cost;//添加到总成本中 回显“
  • ”。“\n”; 回显“”。“\n”; 回显“”。“\n”; 回显“”。“\n”; 回显'.$name'.''。“\n”; 回显'Detaljer'。“\n”; 回显“”。“\n”; 回显“”。“\n”; 回显“”。数字格式((浮动)$行成本,2',,''。''。'\n; 回显“”。“\n”; 回显“
  • ”。“\n”; } } 回显“
”。“\n”; } 否则{ //否则,告诉用户他们的购物车中没有商品 //echo“您的购物车中没有商品。”; }
现在,您可以删除一个项目,而不必将所有其他项目设置为零,但它也可以忽略产品的数量。例如,如果我有一个价格为100的产品,并且我将数量/金额设置为5,它仍然只显示100,而不是500。您需要在交换机中写入一个案例“更新”。您需要实现该功能,以确保价格反映所需的数量。如果我删除其中一个项目,则每个项目的数量/金额仍将设置为零。这次我不知道为什么。尝试将该页面的错误报告设置为“开”,以查看任何警告/通知。为此,将其放在php文件的第一行:
error\u reporting(E\u ALL);ini设置(“显示错误”,真)
//if the cart isn't empty show the cart
if($_SESSION['cart']) {
    echo '<ul id="cart-items">'."\n";

    $productIds = implode(",", array_keys($_SESSION['cart']));

    $sql = "
        SELECT
            single_partners.single_id AS product_id,
            single_partners.partner_id,
            single_partners.price,
            partners.name,
            partners.logo,
            partners.type

        FROM single_partners
        INNER JOIN partners
            ON partners.partner_id = single_partners.partner_id
        WHERE single_id IN ({$productIds})
    ";
    $result = mysql_query($sql);

    $logo_dir = "media/partners/build/color/";
    if(mysql_num_rows($result) > 0) {
        while($row = mysql_fetch_array($result)) {
            $product_id = $row['product_id'];
            $partner_id = $row['partner_id'];
            $partner_price = $row['price'];
            $name = $row['name'];   
            $logo = $row['logo'];
            $type = $row['type'];
            $quantity = $_SESSION['cart'][$product_id];

            $line_cost = $partner_price * $quantity; //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">Detaljer</span>'."\n";
            echo '</div>'."\n";
            echo '<div class="price"><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 '</ul>'."\n";
}
else{
    //otherwise tell the user they have no items in their cart
    //echo "You have no items in your shopping cart.";
}