2

我想建立一个简单的购物场所,但我目前在构建时遇到了一些问题。我如何将产品添加到我的购物车中,这是我目前拥有的。如果用户决定在模态选择中找到产品,或者如果决定使用自动完成搜索框(按 Enter 后添加产品),我还希望用户如何使用会话来完成此操作?我不想使用购物车库 codeigniter 来做这件事。我不能使用除 codeigniter 之外的任何其他库和框架。

销售_添加

public function add_cart(){
        $array = $this->products->search();
        $cart_products = [];
        foreach ($array as $value) {
            $cart_products[] = array(
                'id' => md5($value->id), 
                'name' => $value->description,
                'qty' => $value->stock,
                'price'  => $value->sale_price,

            );

            $this->session->set_userdata('cart_products',$cart_products);
        }
    }

阿贾克斯

$('body').on('click', '.add_product', function(e) {
      alert(1)
  });

桌子

div class="table-responsive">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Item Name</th>
                                            <th>Price</th>
                                            <th>Qty.</th>
                                            <th>Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            info once the cart if added
                                        </tr>
                                    </tbody>
                                </table>
                            </div>

搜索框_modal_search

4

1 回答 1

1

You are on the right track to build your cart. Following your request (a cart on session variable) here is a sample code with notes.

You must check the documentation in codeigniter about:

1.Sessions

2.How to get user input

IMPORTANT

If you do not want to use other frameworks than CodeIgniter you still need to check:

  1. The qty of the item recently added must not exceed the stock of the product

  2. You need to validate that the price is equals the actual price in the dataBase (this last point will depend on the needs of your system)

LAST NOTE

To debug the cart you can use the following line of code

print_r($this->session->userdata('cart_products'));  

Sending this to the view or controller will show you if your cart is properly stored in the session variable.

Please note that this is the solution for CodeIgniter only.

And after all my speach here is the code, hope this helps you:

/*Your function*/
public function add_cart(){

    /*We need to get the data from the user either via AJAX or via form submit*/
    $md5Id = md5($this->input->post("id"));      
    $name = $this->input->post("name");      

    /*We need to make sure the data received is a number*/
    if($this->input->post("qty")>=1){
        /*To prevent tricky data we need to round numbers to prevent any undesirable stuff here*/
        $qty = ceil($qty);
    }else{
        $qty = 1;
    }

    /*You need to get the price from the DATABASE, for the excersice I will use a fixed price*/
    $price= 1500;      


    /*Retreive the cart from the session*/
    $userCart = $this->session->userdata('cart_products');

    /*Validate if the user has a cart*/
    if($userCart!=null){

      /*We check if the user added the item before*/
      $findItem = $this->findItem($userCart, $md5Id);

      /*If findItem is not equals 0*/
      if($findItem!=0){

          /*We declare the variable of the index to remove*/
          $cartIndex = $findItem["arrayIndex"];

          /*We get the qty of the item*/
          $qtyItem = $userCart[$cartIndex]["qty"];

          /*We create the new sum of the */
          $qty = $qty + $qtyItem;
          /*We establish the new qty for that item*/
          $userCart[$cartIndex]["qty"] = $qty;
      }
      /*We need to replace the older cart with the new one*/
      $this->session->set_userdata('cart_products', $userCart);

    }else{
        $userCart = array();
        $item = array(
            'id' => $md5Id, 
            'name' => $name,
            'qty' => $qty,
            'price'  => $price,
        );

        /*In case the user does not have a cart we create one*/
        $userCart[] = $item;
        $this->session->set_userdata('cart_products', $userCart);
    }
}

/*Search item in cart session*/
public function search_cart(){

    /*We need to get the data from the user either via AJAX or via form submit*/
    $name = $this->input->post("name");      

    /*Retreive the cart from the session*/
    $userCart = $this->session->userdata('cart_products');

    /*Validate if the user has a cart*/
    if($userCart!=null){

        /*We check if the user added the item before*/
        $findItems = $this->findByName($userCart, $name);

        /*If findItems is not equals 0*/
        if($findItems!=0){

            /*We return the items found in the cart as per search criteria, this is returned in json in case this needs to be readed via AJAX for example AND we use ECHO in case this thing is the controller*/
            echo json_encode($findItems);
        }
    }
}    

/*Function to find the cart item*/
public function findItem($cart, $md5Id){

   /*We iterate over the cart*/
   foreach($cart as $key=>$item){

      /*Check if any id in the cart match your $md5Id*/
      if($item["id"]==$md5Id){

        /*In case this is found we return an array with the index of the array and qty*/
        return array("arrayIndex"=>$key, "qty"=>$item["qty"]);

      }
   }

   /*In case there is no item found in the cart*/
   return 0;
}

/*Function to find the cart when user types a search criteria*/
public function findByName($cart, $userInput){

    $itemsFound = array();
   /*We iterate over the cart*/
   foreach($cart as $key=>$item){

        /*Check if any id in the cart match via user Input*/
        if (strpos($item["name"], $userInput) !== false) {
            $itemsFound[] =  $item;
        }            
   }
    /*If is not empty the items found we return the array of items*/
    if(!empty($itemsFound)){
        return $itemsFound;
    }
   /*In case there is no item found in the cart*/
   return 0;
}    
于 2018-05-03T23:29:20.953 回答