欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php 购物车的简单实现代码与示例

程序员文章站 2022-03-16 18:30:22
...
  1. session_start();

  2. $conn=mysql_connect("localhost","root","admin");
  3. mysql_select_db("songyu");
  4. //检查数组元素出现次数
  5. function check_count($array,$element)
  6. {
  7. $times=0;
  8. for($i=0;$i {
  9. if($element==$array[$i])
  10. {
  11. $times++;
  12. }
  13. }
  14. return $times;
  15. }
  16. if(isset($_GET["p_id"]))
  17. {
  18. $p_id=$_GET["p_id"];
  19. }
  20. $total_price=0;

  21. array_push($_SESSION["cart"], $p_id);
  22. $cart=$_SESSION["cart"];
  23. echo "your cart:
    ";
  24. $new_array=array_count_values($cart);
  25. foreach ($new_array as $key => $value)
  26. {
  27. $sql="select * from product where id='".$key."'";
  28. $result=mysql_query($sql);
  29. $out=mysql_fetch_array($result);
  30. echo $out[name]."---个数:".$value."--".($out[price]*$value)."
    ";
  31. $total_price=$total_price+($out[price]*$value);
  32. }
  33. echo "

    ";
  34. echo "-----------总价--------------
    ";
  35. echo $total_price;
  36. ?>
  37. 回s
复制代码

2、login.php 登录页

  1. if(isset($_SESSION["user"]))
  2. {
  3. unset($_SESSION["user"]);
  4. }
  5. if(isset($_SESSION["cart"]))
  6. {
  7. unset($_SESSION["cart"]);
  8. }
  9. ?>
  10. username:

  11. password:

复制代码

3、product.php 产品页

  1. session_start();
  2. $conn=mysql_connect("localhost","root","admin");
  3. mysql_select_db("songyu");
  4. $sql_product="select * from product";
  5. $res=mysql_query($sql_product);
  6. if(!isset($_SESSION["cart"]))
  7. {
  8. $_SESSION["cart"]=array();
  9. }
  10. while($out2=mysql_fetch_array($res))
  11. {
  12. echo "".$out2[name]."
    ";
  13. echo $out2[price]."
    ";
  14. echo "
    ";
  15. }
  16. ?>
复制代码

4、product_index.php 产品索引页

  1. $conn=mysql_connect("localhost","root","admin");
  2. mysql_select_db("songyu");
  3. $sql="select * from user where username='".$_POST["username"]."' and password='".$_POST["password"]."'";
  4. $result=mysql_query($sql);
  5. $out=mysql_fetch_array($result); //bbs.it-home.org
  6. if(!$out)
  7. {
  8. echo "wrong!";
  9. }
  10. else
  11. {
  12. $_SESSION["user"]=$out[id];
  13. echo "";
  14. }
  15. ?>
复制代码