简体   繁体   English

购物车问题与更新数量和从购物车中删除项目

[英]Shopping cart issue with updating the quantity and removing items from the cart

I am trying to work on a homework assignment involving adding items to a cart and updating them and removing items from the cart. 我正在努力完成一项家庭作业,包括将物品添加到购物车并更新它们并从购物车中移除物品。 So far I have been able to add items but now I'm facing issues with the updating of the quantity and removing of items. 到目前为止,我已经能够添加项目,但现在我面临更新数量和删除项目的问题。 Could anyone please assist me? 有人可以帮助我吗? Thank you. 谢谢。

<?php
session_start();
include 'dbconnect.php';
include 'functions.php';

// Create an empty cart if it does not exist 
if (!isset($_SESSION['cart'])) {
$_SESSION['cart']=array();
}
// Add an item to the cart

$title = $_GET['title'];

$quantity = $_GET['quantity'];

if ($quantity > 0) { 
    $_SESSION['cart'][$title]= round($quantity,0);

    //create an array of current items in the cart
    $items = array();

    if(isset($_GET['remove']) && (!empty($_GET['remove'] || 
$_GET['remove'] == 0))){
    unset($_SESSION['cart'][$_GET['remove']]);
}

?>
 <!DOCTYPE html>
 <html>    
 <head>
 <title>BOOK SHOP</title>
 <link rel="stylesheet" type="text/css" href= "main.css" />
 </head>
<body>
<form>
<input type="button" value="Go back" onclick="history.back()">
 </form>

    <h1>Your Cart </h1> 

    <?php
    $grand_total = 0;

    echo '<table border = "1">  <tr> <th>  Book Name </th>  <th>  Price 
    </th> <th> Qty</th> <th> Total</th></tr> '; 
    foreach ($_SESSION['cart']as $title => $quantity) {

        // get book data
        $result =get_product_data($title);


        $items[$title]
        ['bookname'] =$result[0][2];
        $items[$title]
        ['listPrice'] = $result[0][3]; 
        $items[$title]
        ['quantity']=$quantity;

        $book_total = $result[0][3] * $quantity;
        $grand_total +=$book_total;

        echo  '<tr>'; 
        echo  '<td>' . $items[$title]['bookname'] . '</td>';
        echo  '<td>' . $items[$title]['listPrice'] . '</td> ';
        echo  "<td><input type='text' class='form-control' 
     name='value'".$items[$title]['quantity'] ."'></td>";

        echo  '<td>' .  sprintf('$%.2f',$book_total) . '</td>';
        echo '<td><a href="?remove=' . $title . '">remove</a></td>';
        echo  '</tr>';


    }
    }   
    echo "<td><input type= 'submit' name='even' value='Update' class='btn 
  btn-warning'></td>";
    echo '<tr> <td>&nbsp</td>     <td>&nbsp</td>  <td>TOTAL</td> <td>' . 
  sprintf('$%.2f',$grand_total) . '</td> ';
    echo '</table>';    
    ?>


   </body>
    </html>

The expected result should be when I remove an item, it removes the item. 预期的结果应该是当我删除一个项目时,它会删除该项目。 When updating the quantity, it will update the price and quantity. 更新数量时,它将更新价格和数量。 Instead I receive errors related to an undefined variable and index: 相反,我收到与未定义的变量和索引相关的错误:

When I remove an item, I get the following: 当我删除一个项目时,我得到以下内容:

Notice: Undefined index: title in C:\\xampp\\htdocs\\book_apps\\Book Database Connect\\add_to_cart.php on line 12 注意:未定义的索引:第12行的C:\\ xampp \\ htdocs \\ book_apps \\ Book Database Connect \\ add_to_cart.php中的标题
Notice: Undefined index: quantity in C:\\xampp\\htdocs\\book_apps\\Book Database Connect\\add_to_cart.php on line 14 注意:未定义的索引:第14行的C:\\ xampp \\ htdocs \\ book_apps \\ Book Database Connect \\ add_to_cart.php中的数量
Notice: Undefined variable: grand_total in C:\\xampp\\htdocs\\book_apps\\Book Database Connect\\add_to_cart.php on line 73 TOTAL $0.00 注意:未定义的变量:C:\\ xampp \\ htdocs \\ book_apps中的grand_total \\第73行的书籍数据库连接\\ add_to_cart.php总计$ 0.00

So, I spent a good amount of time looking over your code to see what you're trying to achieve. 所以,我花了很多时间查看你的代码,看看你想要实现的目标。 Without writing everything out for you, here's a very basic example with no validation to get you started. 如果不为您编写所有内容,这里是一个非常基本的示例,没有验证可以帮助您入门。 You can add in the product info from your database, as well as the actual online store piece that would allow you to add items to your cart, etc. I added a form with method "POST" to handle submitting updated quantities or removing an item. 您可以添加数据库中的产品信息,以及允许您向购物车添加商品的实际在线商店信息等。我添加了一个方法"POST"form来处理提交更新的数量或删除项目。 There are plenty of other better alternatives out there for handling this sort of cart logic , but as it looks like you're newer to PHP, I figured I would help with some basics to give you an idea of how things function within an OOP paradigm. 还有很多其他更好的选择来处理这种类型的购物车逻辑 ,但是因为看起来你是PHP的新手,我想我会帮助你了解一些基本知识,让你了解事物在OOP范式中的运作方式。

<?php
session_start();

/* for testing purposes, unset cart session on each run of code if you need to simulate
adding new items to the cart */
//unset($_SESSION['cart']); 

// Create an empty cart if it does not exist
if (!isset($_SESSION['cart']))
{
    $_SESSION['cart'] = [];

    // For testing purposes, add cart session data on each run of code
    // This info would come from database and be set here via ADD button, etc.
    // Comment out if you want nothing in cart on run of page
    $_SESSION['cart'][] = array('book_id' => 1, 'quantity' => 2);
    $_SESSION['cart'][] = array('book_id' => 2, 'quantity' => 1);

    // DEBUGGING
    //echo "<pre>";
    //print_r($_SESSION['cart']);
    //exit;
}

function updateItem($book_id, $quantity, $action) {
    foreach ($_SESSION['cart'] as $key => $cart_item)
    {
        if($cart_item['book_id'] === $book_id) {
             if($action === 'remove') {
               unset($_SESSION['cart'][$key]);
             } else if($action === 'update') {
                $_SESSION['cart'][$key]['quantity'] = $quantity;
             } else {
               // some other default action   
             }
            return;
        }
    }
}

function updateBulkItems($itemsWithQuantity) {
    foreach($itemsWithQuantity as $key => $itemArr) {     
        $book_id = key($itemArr);
        $quantity = $itemArr[$book_id];
        updateItem($book_id, $quantity, 'update');
    }
}

// Process cart actions update/remove
if (isset($_POST) && !empty($_POST) && is_array($_POST))
{
    // DEBUGGING
    //echo "<pre>";
    //print_r($_POST);
    //exit;

    $postedData = $_POST;
    switch($postedData) {     
        case isset($postedData['remove']):
           // do remove logic here w/ database/session
           updateItem(key($postedData['remove']), null, 'remove');
        break;

        case isset($postedData['update']):
           // do update logic here w/ database/session
           updateBulkItems($postedData['quantity']);
        break;

        default:

        break;
    }    
}

$grand_total = 0;
?>
<!DOCTYPE html>
<html>
    <head>
        <title>
            BOOK SHOP
        </title>
        <link rel="stylesheet" type="text/css" href= "main.css" />
    </head>
    <body>
        <form>
            <input type="button" value="Go back" onclick="history.back()">
        </form>
        <h1>
            Your Cart 
        </h1>
        <?php

/**
* This product info would come from database, etc.
* Find book info from ID passed in
* @param $book_id
*/
function get_product_data($book_id) {

    // Mock database return data..
    $product_array = [];
    $product_array[] = array('id' => 1, 'title' => 'Title 1', 'book_name' => 'Book Name 1', 'total' => 5.99);
    $product_array[] = array('id' => 2, 'title' => 'Title 2', 'book_name' => 'Book Name 2', 'total' => 3.99);

    foreach($product_array as $key => $product) {
        if($product['id'] === $book_id) {
             return $product;   
        }
    }    
    return [];
}

echo '<form id="cart_form" method="POST">';
echo '<table border="1"><tr><th>Book Name</th><th>Price</th><th>Qty</th><th>Total</th></tr>';

foreach ($_SESSION['cart'] as $key => $cart_item)
{
    // get book data
    $book_id = $cart_item['book_id'];
    $product_info = get_product_data($book_id);
    if(count($product_info) == 0) {
      continue;
    }
    $book_total = $cart_item['quantity'] * $product_info['total'];
    $grand_total += $book_total;
    echo '<tr>';
    echo '<td>' . $product_info['book_name'] . '</td>';
    echo '<td>' . $product_info['total']. '</td> ';
    echo "<td><input type='text' class='form-control' 
name='quantity[][".$book_id."]' value='" . $cart_item['quantity']. "'></td>";
    echo '<td>' . sprintf('$%.2f',  $book_total) . '</td>';
    echo '<td><input type="submit" name="remove['.$book_id.']" value="Remove" class="btn"></a></td>';
    echo '</tr>';
}

if(count($_SESSION['cart']) > 0) {
    echo "<td><input type='submit' name='update' value='Update' class='btn'></td>";
}
echo '<tr> <td>&nbsp</td><td>&nbsp</td><td>TOTAL</td><td>' . sprintf('$%.2f', $grand_total) . '</td>';
echo '</table>';
echo '</form>';
?>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM