Home >Backend Development >PHP Tutorial >PHP shopping cart function implementation code (entry example)

PHP shopping cart function implementation code (entry example)

WBOY
WBOYOriginal
2016-07-25 08:59:311370browse
  1. //Product category page
  2. session_start();//Open session environment
  3. //Determine whether the user has clicked the "Add to Shopping Cart" button
  4. if(isset($_POST[' cart'])){
  5. //Assign value in a loop
  6. foreach($_POST['cart'] as $value){
  7. //If the product is in the shopping cart
  8. //Condition:
  9. //Click "Put" "Add to shopping cart"---array $_SESSION['cart'];
  10. //Determine which product----Determine whether the name of the product appears in the array
  11. //array_key_exists(subscript, array);
  12. if(isset($_SESSION['cart'])&& array_key_exists($value,$_SESSION['cart'])){
  13. $_SESSION['cart'][$value]++;
  14. }else{
  15. //If the product is not in the shopping cart
  16. $_SESSION['cart'][$value]=1;
  17. }
  18. }
  19. }
  20. ?>
  21. Online Mall_php Shopping Cart-bbs.it-home.org
  22. Online Mall

  23. Daily Necessities
  24. Household appliances
  25. Stationary supplies
  26. < a href="carlist.php">View cart
  27. Clear cart
Copy code

2. carlist.php displays the items in the shopping cart

  1. //Display the products in the shopping cart (product name, product quantity)

  2. session_start();
  3. echo "The products you have selected include:
  4. echo "
    ";

  5. //Display the items purchased by the user

  6. //Includes functions :Delete the product
  7. //Modify the quantity of the product
  8. //Edit bbs.it-home.org
  9. //Get user purchase information $_SESSION, display products in a loop
  10. if(isset($_SESSION['cart']) ){
  11. foreach(@$_SESSION['cart'] as $key=>$value){
  12. echo " ";
  13. echo "$key    $value  ";
  14. //One less item
  15. echo "Delete one item";
  16. echo " Delete this item
    ";
  17. }
  18. }
  19. echo "";
  20. echo "Clear shopping cart echo "";
  21. echo " Return to homepage";
  22. ?>
Copy code

3. File cardel.php to clear the shopping cart

  1. session_start();//Open session environment

  2. //Clear the shopping cart

  3. unset($_SESSION['cart'] );
  4. ?>
Copy code

The above code implements the common functions of a shopping cart, displaying product classification and information, processing of products in the shopping cart, etc. I hope to be helpful.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn