Привет, друг! У меня есть небольшой проект в PHP для корзины покупок, и моя проблема в том, что у меня есть один товар с двумя флажками разных цен (цена 1 = 60 долларов США и цена 2 = 20 долларов США), и я не ' Не знаю, как заставить это работать, чтобы добавить товар в корзину с установленными ценами в чекбоксах, чтобы он был функциональным. Проверьте изображение с продуктом. См. Изображение здесь . Обратите внимание, что в mysql дБ в таблице продуктов у меня есть цена и цена2. Любая помощь приветствуется!
Индекс Php код:
<?php
// Initialize shopping cart class
include_once 'Cart.class.php';
$cart = new Cart;
// Include configuration file
include_once 'config.php';
// Include database connection file
include_once 'dbConfig.php';
?>
<!-- Bootstrap core CSS -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/plugins/bootstrap/css/bootstrap.min.css">
<link href="../assets/css/style.min.css" rel="stylesheet">
<div class="cart-view">
<a href="viewCart.php" title="View Cart"><i class="icart"></i> (<?php echo ($cart->total_items() > 0)?$cart->total_items().' Items':'Gol'; ?>)</a>
</div>
<section class="main-section">
<div class="our-best-courses best-courses-list ">
<div class="container">
<div class="row">
<?php
// Fetch products from the database
$results = $db->query("SELECT * FROM products WHERE status = 1");
while($row = $results->fetch_assoc()){
?>
<div class="col-xl-3 col-lg-4 col-md-6 col-sm-6">
<div class="courses-box">
<div class="courses-img img_hover_effect"><img src="<?php echo $row['image']; ?>" alt="Oana Ionita"></div>
<div class="courses-cnt">
<div class="text-center courses-name"><?php echo $row['name']; ?></div>
<p class="categorie text-center"><?php echo $row['description']; ?></p>
<ul class="color-info clearfix list-unstyled ">
<li>
<div class="form-check checkbox-rounded checkbox-living-coral-filled ">
<input type="checkbox" class="form-check-input filled-in" id="individual">
<label class="form-check-label" for="individual">Individual:</label>
<span class="text-danger"><?php echo $row['price']; ?> <?php echo PAYPAL_CURRENCY; ?> / Hour</span>
</div>
</li>
<li>
<div class="form-check checkbox-rounded checkbox-living-coral-filled ">
<input type="checkbox" class="form-check-input filled-in" id="grup">
<label class="form-check-label" for="grup">Group:</label>
<span class="text-danger"><?php echo $row['pricet']; ?> <?php echo PAYPAL_CURRENCY; ?> / Hour</span>
</div>
</li>
</ul>
<!-- Display the payment button. -->
<center> <a href="cartAction.php?action=addToCart&id=<?php echo $row["id"]; ?>" class="btn btn-primary btn-round displayblock">Add to cart</a></center>
</form>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
</section>
Cart.class Php:
<?php
// Start session
if(!session_id()){
session_start();
}
/**
* Shopping Cart Class
*
* @package PHP Library
* @category Shopping Cart
* @author CodexWorld Dev Team
* @link https://www.codexworld.com
*/
class Cart {
protected $cart_contents = array();
public function __construct(){
// get the shopping cart array from the session
$this->cart_contents = !empty($_SESSION['cart_contents'])?$_SESSION['cart_contents']:NULL;
if ($this->cart_contents === NULL){
// set some base values
$this->cart_contents = array('cart_total' => 0, 'total_items' => 0);
}
}
/**
* Cart Contents: Returns the entire cart array
* @param bool
* @return array
*/
public function contents(){
// rearrange the newest first
$cart = array_reverse($this->cart_contents);
// remove these so they don't create a problem when showing the cart table
unset($cart['total_items']);
unset($cart['cart_total']);
return $cart;
}
/**
* Get cart item: Returns a specific cart item details
* @param string $row_id
* @return array
*/
public function get_item($row_id){
return (in_array($row_id, array('total_items', 'cart_total'), TRUE) OR ! isset($this->cart_contents[$row_id]))
? FALSE
: $this->cart_contents[$row_id];
}
/**
* Total Items: Returns the total item count
* @return int
*/
public function total_items(){
return $this->cart_contents['total_items'];
}
/**
* Cart Total: Returns the total price
* @return int
*/
public function total(){
return $this->cart_contents['cart_total'];
}
/**
* Insert items into the cart and save it to the session
* @param array
* @return bool
*/
public function insert($item = array()){
if(!is_array($item) OR count($item) === 0){
return FALSE;
}else{
if(!isset($item['id'], $item['name'], $item['price'], $item['qty'])){
return FALSE;
}else{
/*
* Insert Item
*/
// prep the quantity
$item['qty'] = (float) $item['qty'];
if($item['qty'] == 0){
return FALSE;
}
// prep the price
$item['price'] = (float) $item['price'];
// create a unique identifier for the item being inserted into the cart
$rowid = md5($item['id']);
// get quantity if it's already there and add it on
$old_qty = isset($this->cart_contents[$rowid]['qty']) ? (int) $this->cart_contents[$rowid]['qty'] : 0;
// re-create the entry with unique identifier and updated quantity
$item['rowid'] = $rowid;
$item['qty'] += $old_qty;
$this->cart_contents[$rowid] = $item;
// save Cart Item
if($this->save_cart()){
return isset($rowid) ? $rowid : TRUE;
}else{
return FALSE;
}
}
}
}
/**
* Update the cart
* @param array
* @return bool
*/
public function update($item = array()){
if (!is_array($item) OR count($item) === 0){
return FALSE;
}else{
if (!isset($item['rowid'], $this->cart_contents[$item['rowid']])){
return FALSE;
}else{
// prep the quantity
if(isset($item['qty'])){
$item['qty'] = (float) $item['qty'];
// remove the item from the cart, if quantity is zero
if ($item['qty'] == 0){
unset($this->cart_contents[$item['rowid']]);
return TRUE;
}
}
// find updatable keys
$keys = array_intersect(array_keys($this->cart_contents[$item['rowid']]), array_keys($item));
// prep the price
if(isset($item['price'])){
$item['price'] = (float) $item['price'];
}
// product id & name shouldn't be changed
foreach(array_diff($keys, array('id', 'name')) as $key){
$this->cart_contents[$item['rowid']][$key] = $item[$key];
}
// save cart data
$this->save_cart();
return TRUE;
}
}
}
/**
* Save the cart array to the session
* @return bool
*/
protected function save_cart(){
$this->cart_contents['total_items'] = $this->cart_contents['cart_total'] = 0;
foreach ($this->cart_contents as $key => $val){
// make sure the array contains the proper indexes
if(!is_array($val) OR !isset($val['price'], $val['qty'])){
continue;
}
$this->cart_contents['cart_total'] += ($val['price'] * $val['qty']);
$this->cart_contents['total_items'] += $val['qty'];
$this->cart_contents[$key]['subtotal'] = ($this->cart_contents[$key]['price'] * $this->cart_contents[$key]['qty']);
}
// if cart empty, delete it from the session
if(count($this->cart_contents) <= 2){
unset($_SESSION['cart_contents']);
return FALSE;
}else{
$_SESSION['cart_contents'] = $this->cart_contents;
return TRUE;
}
}
/**
* Remove Item: Removes an item from the cart
* @param int
* @return bool
*/
public function remove($row_id){
// unset & save
unset($this->cart_contents[$row_id]);
$this->save_cart();
return TRUE;
}
/**
* Destroy the cart: Empties the cart and destroy the session
* @return void
*/
public function destroy(){
$this->cart_contents = array('cart_total' => 0, 'total_items' => 0);
unset($_SESSION['cart_contents']);
}
}
CartAction Php:
<?php
// Initialize shopping cart class
require_once 'Cart.class.php';
$cart = new Cart;
// Include the database config file
require_once 'dbConfig.php';
// Default redirect page
$redirectLoc = 'index.php';
// Process request based on the specified action
if(isset($_REQUEST['action']) && !empty($_REQUEST['action'])){
if($_REQUEST['action'] == 'addToCart' && !empty($_REQUEST['id'])){
$productID = $_REQUEST['id'];
// Get product details
$query = $db->query("SELECT * FROM products WHERE id = ".$productID);
$row = $query->fetch_assoc();
$itemData = array(
'id' => $row['id'],
'name' => $row['name'],
'price' => $row['price'],
'pricet' => $row['pricet'],
'qty' => 1
);
// Insert item to cart
$insertItem = $cart->insert($itemData);
// Redirect to cart page
$redirectLoc = $insertItem?'index.php':'index.php';
}elseif($_REQUEST['action'] == 'updateCartItem' && !empty($_REQUEST['id'])){
// Update item data in cart
$itemData = array(
'rowid' => $_REQUEST['id'],
'qty' => $_REQUEST['qty']
);
$updateItem = $cart->update($itemData);
// Return status
echo $updateItem?'ok':'err';die;
}elseif($_REQUEST['action'] == 'removeCartItem' && !empty($_REQUEST['id'])){
// Remove item from cart
$deleteItem = $cart->remove($_REQUEST['id']);
// Redirect to cart page
$redirectLoc = 'viewCart.php';
}elseif($_REQUEST['action'] == 'placeOrder' && $cart->total_items() > 0){
$redirectLoc = 'checkout.php';
// Store post data
$_SESSION['postData'] = $_POST;
$first_name = strip_tags($_POST['first_name']);
$last_name = strip_tags($_POST['last_name']);
$email = strip_tags($_POST['email']);
$phone = strip_tags($_POST['phone']);
$address = strip_tags($_POST['address']);
$errorMsg = '';
if(empty($first_name)){
$errorMsg .= 'Please enter your first name.<br/>';
}
if(empty($last_name)){
$errorMsg .= 'Please enter your last name.<br/>';
}
if(empty($email)){
$errorMsg .= 'Please enter your email address.<br/>';
}
if(empty($phone)){
$errorMsg .= 'Please enter your phone number.<br/>';
}
if(empty($address)){
$errorMsg .= 'Please enter your address.<br/>';
}
if(empty($errorMsg)){
// Insert customer data in the database
$insertCust = $db->query("INSERT INTO customers (first_name, last_name, email, phone, address) VALUES ('".$first_name."', '".$last_name."', '".$email."', '".$phone."', '".$address."')");
if($insertCust){
$custID = $db->insert_id;
// Insert order info in the database
$insertOrder = $db->query("INSERT INTO orders (customer_id, grand_total, created, status) VALUES ($custID, '".$cart->total()."', NOW(), 'Pending')");
if($insertOrder){
$orderID = $db->insert_id;
// Retrieve cart items
$cartItems = $cart->contents();
// Prepare SQL to insert order items
$sql = '';
foreach($cartItems as $item){
$sql .= "INSERT INTO order_items (order_id, product_id, quantity) VALUES ('".$orderID."', '".$item['id']."', '".$item['qty']."');";
}
// Insert order items in the database
$insertOrderItems = $db->multi_query($sql);
if($insertOrderItems){
// Remove all items from cart
$cart->destroy();
// Redirect to the status page
$redirectLoc = 'orderSuccess.php?id='.$orderID;
}else{
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Some problem occurred, please try again.';
}
}else{
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Some problem occurred, please try again.';
}
}else{
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Some problem occurred, please try again.';
}
}else{
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Please fill all the mandatory fields.<br>'.$errorMsg;
}
$_SESSION['sessData'] = $sessData;
}
}
// Redirect to the specific page
header("Location: $redirectLoc");
exit();