Как я могу вставить количество в эту корзину php

0

Я успешно добавил элементы в корзину покупок. Однако я не могу добавить его количество. Я знаю, что проблема находится где-то в addtocart, где я не могу передать значение из индекса на следующую страницу. Я все еще новичок в этом, поэтому я понятия не имею, как это исправить. Я попытался использовать сеанс, но он все еще не работает

Это мой код в index.php:

<html>
    <head>
        <meta charset="UTF-8">
        <title>Innisnotfree</title>
    </head>
    <body>
        <?php
            session_start();
           
            include'header.php';
            include'nav.php';
            include "connection.php";
            
            $sql = "SELECT * FROM products";
            $res = mysqli_query($connection, $sql);
        ?>
        
        <div class="container">
            
            <div class="row">
               
                <?php while($r = mysqli_fetch_assoc($res)){ ?>
                <div class="col-sm-6 col-md-3">
                    <div class="thumbnail">
                        <img src="<?php echo $r['image'];?>" alt="<?php echo $r['title']?>">
                        <div class="caption">
                            <form name="form1" id="form1" method="POST" action="addtocart.php?id=<?php echo $r['id']?>">
                                <h3><?php echo $r['title']?></h3>
                                <p> <?php echo $r['description']?></p>
                                <p><?php echo $r['price']?></p>
                                <p><input type="number" name="quantity" id="quantity" class="form-control"/></p>
                                <p><input type="submit" name="add_to_cart" id="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Add to Cart"/></p>
                            </form>
                        </div>
                    </div>
                </div>
                <?php } ?>
            </div>
        </div>
        
        <?php include('footer.php')?>
 
    </body>
</html>

Это мой addtocart.php

<?php
    session_start();
    
if(isset($_SESSION['cart']) & !empty($_SESSION['cart'])){
	$items = $_SESSION['cart'];
	$cartitems = explode(",", $items);
	$items .= "," . $_GET['id'];
        if($_SERVER["REQUEST_METHOD"]=="POST"){
        $quantity = $_POST["quantity"];}
	header('location: index.php?status=success');
}else{
	$items = $_GET['id'];
	$_SESSION['cart'] = $items;
         if($_SERVER["REQUEST_METHOD"]=="POST"){
        $_POST["quantity"] = $quantity ;}
	header('location: index.php?status=success');
          
}
 ?>

Это мой cart.php:

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
            session_start();
            require_once('connection.php');
            include('header.php');
            include('nav.php');
            
            $items = $_SESSION['cart'];
            if($_SERVER["REQUEST_METHOD"]=="POST"){
                $quantity = $_POST["quantity"];
            }
            $cartitems = explode(",", $items);
            
       
        ?>
        
         
        <div class="container">
            <div class="row">
                <table class="table">
                    <tr>
                        <th>S.NO</th>
                        <th>Item Name</th>
                        <th>Quantity</th>
                        <th>Price </th>
                    </tr>
                    <?php
                        $total = 0;
                        $i =1;
                        
                        foreach ($cartitems as $key=>$id){
                            $sql = "SELECT * FROM products WHERE id = $id";
                            $res=  mysqli_query($connection, $sql);
                            if(empty($_SESSION['cart'])){
                                $r = 0;
                                
                            }
                            else{
                                 $r = mysqli_fetch_assoc($res);
      
                            }
                        ?>
                   
                    <tr>
                        <td><?php echo $i; ?></td>
                        <td><a href="delcart.php?remove=<?php echo $key; ?>">Remove</a><?php echo $r['title'];?></td>
                        <td><?php  if($_SERVER["REQUEST_METHOD"]=="POST"){echo $_POST["quantity"];};?></td>
                        <td>$<?php echo $r['price'];?></td>
                    </tr>
                    <?php
                    
                        $total = $total +  $r['price'];
                        $i++;
                        }
                    ?>
                    <tr>
                        <td><strong>Total Price</strong></td>
                        <td><strong>$<?php echo $total; ?></strong></td>
                        <td><a href="#" class="btn btn-info">Checkout</a></td>
                    </tr>
                </table>
            </div>
        </div>
        <?php 
            include 'footer.php';
        ?>
        
       
    </body>
</html>

1 ответ

0

см. мой класс для свинг-тележки, и вы можете изменить его, как хотите.

class cart {
/**
 * add product to cart by id and quantity
 * @param type $pid product id
 * @param type $quantity 
 */
function add($pid,$quantity){

/*if cart dosen't exist initialize it and add the first product*/
    if(!isset($_SESSION['cart'])){
        $_SESSION['cart']=array();
        $_SESSION['cart'][0]['productid']=$pid;
        $_SESSION['cart'][0]['quantity']=$quantity;
        echo 'Product successfully added';
    }
/*else if cart exist check if product exist to change quantity else add new product*/
    else {
/*if exist change quantity*/
        if($this->isexist($pid,$quantity)){
            echo 'Quantity updated successfully';
        }
/*else add new product in cart*/
        else{
            $m=$_SESSION['cart'];
            $max=count($m);
            $_SESSION['cart'][$max]['productid']=$pid;
            $_SESSION['cart'][$max]['quantity']=$quantity;
            echo 'Product successfully added';
        }
    }

}

/**
 * check if product alredy exist in cart or not
 * @param type $pid product id
 * @param type $quantity
 * @return boolean if true the product is exist and the quantity change successfully
 */
function isexist($pid,$quantity) {
    $m=$_SESSION['cart'];
    $max=count($m);
    for($i=0;$i<$max;$i++){
        if($pid==$_SESSION['cart'][$i]['productid']){
            $_SESSION['cart'][$i]['quantity']=$quantity;
            return true;
        }
    }
    return false;

}

/**
 * delete product by product id
 * @param type $pid product id
 */
function delete($pid){
    $m=$_SESSION['cart'];
    $max=count($m);
    for($i=0;$i<$max;$i++){
        if($pid==$_SESSION['cart'][$i]['productid']){
        unset($_SESSION['cart'][$i]);
        $_SESSION['cart']=array_values($_SESSION['cart']);$_SESSION['cart'.'num']-=1;break;
        }
    }
}

/**
 * change quantity of exist product
 * @param type $pid product id
 * @param type $quantity
 */
function modify($pid,$quantity){
    $m=$_SESSION['cart'];
    $max=count($m);

    if($quantity>0){
        for($i=0;$i<$max;$i++){
            if($pid==$_SESSION['cart'][$i]['productid']){
                $_SESSION['cart'][$i]['quantity']=$quantity;break;
            }
        }
    }

    else {$this->delete($pid);}

}

/**
 * show all items in your cart
 */
function show_cart() {

    $max=count($_SESSION['cart']);
    for($i=0;$i<$max;$i++){
        echo 'id=>'.$_SESSION['cart'][$i]['productid'].
             'quantity=>'.$_SESSION['cart'][$i]['quantity'].'<br>';
    }
}

}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню