0

Web サイトのショッピング カートを作成するときに、個々の製品の機能を追加および削除しました。製品を追加すると、現在の行ではなく、テーブルの新しい行に追加されます。

製品を追加および削除するためのコードは次のとおりです。

function addproduct($product_id, $product_qty){

$q = "SELECT p_name FROM Product WHERE product_id = $product_id LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_name = $row['p_name']; //get the product name from product id because it is better to display name than id in the cart
if (isset($_SESSION['cart'])){  //if shopping cart is not empty
    $cart = $_SESSION['cart'];
    if (array_key_exists($product_name, $cart)){ //if the product exists, update                        quantity
        $cart[$product_name] += $product_qty;
    }
    else {  //otherwise, add new product-quantity pair to the array
        $cart[$product_name] = $product_qty;
    }
$_SESSION['cart'] = $cart; //write the updated array back to session variable
}
else { //if shopping cart is empty
    $cart = array($product_name=>$product_qty); //add product and quantity to the                           shopping cart
    $_SESSION['cart'] = $cart; //write the updated array back
}
mysqli_free_result($result);
}
function deleteproduct($product_id, $product_qty){
$q = "SELECT p_name FROM Product WHERE product_id = $product_id LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_name = $row['p_name'];
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
    $cart = $_SESSION['cart'];
    if (array_key_exists($product_name, $cart)){ //if product exists, update quantity
        $cart[$product_name] -= $product_qty;
        if ($cart[$product_name] == 0){ //if the qty 0, delete key
            unset($cart[$product_name]);
        }
    }
    else { //exception
        echo "<p>Error1</p>";
    }
    $_SESSION['cart'] = $cart; //write array back to session variable
} else {
    echo "<p>Error2</p>";
}
mysqli_free_result($result);
}
4

1 に答える 1

0

たぶんこれを切る

if (isset($_SESSION['cart'])){  //if shopping cart is not empty
    $cart = $_SESSION['cart'];
    if (array_key_exists($product_name, $cart)){ //if the product exists, update                        quantity
        $cart[$product_name] += $product_qty;
    }
    else {  //otherwise, add new product-quantity pair to the array
        $cart[$product_name] = $product_qty;
    }
$_SESSION['cart'] = $cart; //write the updated array back to session variable
}
else { //if shopping cart is empty
    $cart = array($product_name=>$product_qty); //add product and quantity to the                           shopping cart
    $_SESSION['cart'] = $cart; //write the updated array back
}

3 行に減らして、それでも機能しない場合はお知らせください。

if (!isset($_SESSION['cart'])) $_SESSION['cart']=array();
if (!isset($_SESSION['cart'][$product_name])) $_SESSION['cart'][$product_name]=$product_qty;
else $_SESSION['cart'][$product_name]+=$product_qty;
于 2013-03-12T15:00:07.440 に答える