Итак, я потратил много времени на просмотр вашего кода, чтобы увидеть, чего вы пытаетесь достичь. Не написав все для вас, вот очень простой пример без проверки, чтобы вы начали. Вы можете добавить информацию о товаре из вашей базы данных, а также фактическую часть интернет-магазина, которая позволит вам добавлять товары в корзину и т. Д. Я добавил form
с методом "POST"
для обработки отправки обновленных количеств или удаления пункт. Существует множество других лучших альтернатив для обработки логики корзины такого типа , но, похоже, вы новичок в PHP, я подумал, что помогу с некоторыми основами, чтобы дать вам представление о том, как вещи функционируют в рамках парадигмы ООП.
<?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> </td><td> </td><td>TOTAL</td><td>' . sprintf('$%.2f', $grand_total) . '</td>';
echo '</table>';
echo '</form>';
?>
</body>
</html>