찾다
php教程php手册php购物车实现方法

php购物车实现方法

Jun 13, 2016 am 09:08 AM
php기본사용기능성취하다문서기사방법~의장바구니통과하다

php购物车实现方法

 这篇文章主要介绍了php购物车实现方法,通过4个文件实现购物车的功能,且使用txt文件保存购物车内容,简单实用,需要的朋友可以参考下

 

 

本文实例讲述了php购物车实现方法。分享给大家供大家参考。具体分析如下:

这里我们为你提供个简单的php购物车代码,从增加购物产品与发生购买了,在商城开发中,这个功能是少不了的,我们不需要数据库,用了txt文本文件来操作用户购物的内容.

增加商品到购物车,代码如下:

代码如下:

//
// add_item.php:
// Add an item to the shopping cart.
//
session_start();
if (session_is_registered('cart')) {
session_register('cart');
}

require 'lib.inc.php'; // LoadProducts()

LoadProducts(); // Load products in $master_products_list

// Make $curr_product global
$curr_product = array();

// Loop through all the products and pull up the product
// that we are interested in

foreach ($master_products_list as $prod_id => $product) {
if (trim($prod_id) == trim($_GET[id])) {
$curr_product = $product;
}
}

// Register our session
//session_register('cart');
//if(session_is_registered('cart')) echo "已经注册";

if ($_POST[ordered]) { // If they have chosen the product

array_push($_SESSION[cart][products], array(trim($_POST[id]), $_POST[quantity]));
$_SESSION[cart][num_items] += $_POST[quantity];
}
?>


<br> <?php if ($_POST[ordered]) { ?> <br> 已经添加 <?php echo $curr_product[name]; ?> 到您的购物篮 <br> <?php } else { ?> <br> 添加 <?php echo $curr_product[name]; ?> 到您的购物篮 <br> <?php } ?> <br>




添加至购物篮成功



返回 商品列表页面.

添加 到您的购物篮




商品名称:


商品说明:


商品单价: RMB


商品数量:






 

查看购物车的商品,代码如下:

代码如下:

//
// cart.php:
//
session_start();

require 'lib.inc.php';
//判断购物篮会话变量cart是否注册,不注册则注册cart变量
if (session_is_registered('cart')) {
session_register('cart');
}

// 如果购物篮没有初始化,则初始化购物篮
if (!isset($_SESSION[cart][num_items])) {
$_SESSION[cart] = array("num_items" => 0,
"products" => array());
}
// From site_lib.inc, Loads the $master_products_list array
LoadProducts(); //载入物品列表
?>


演示会话跟踪的购物篮程序




欢迎进入网上商店



if ($_SESSION[cart][num_items]) { // If there is something to show
?>

当前在购物篮里的物品













// Loop through the products
foreach ($_SESSION[cart][products] as $i => $product) {
$product_id = $product[0];
$quantity = $product[1];

$total += $quantity *
(double)$master_products_list[$product_id][price];
?>







}
?>






商品名称

商品说明

单价

数量











value="">




合计:

RMB:





}
?>

商店待出售的商品





我们提供以下商品待售:










// Show all of the products
foreach ($master_products_list as $product_id => $item) {
?>






}

?>

商品名称

商品说明

单价







$


添加至购物篮

 

修改购物车的数量,代码如下:

代码如下:

//
// change_quant.php:
// Change the quantity of an item in the shopping cart.
//
session_start();
if (session_is_registered('cart')) {
session_register('cart');
}

// Typecast to int, making sure we access the
// right element below
$i = (int)$_POST[id];

// Save the old number of products for display
// and arithmetic
$old_num = $_SESSION[cart][products][$i][1];

if ($_POST[quantity]) {
$_SESSION[cart][products][$i][1] = $_POST[quantity]; //change the quantity
} else {
unset($_SESSION[cart][products][$i]); // Send the product into oblivion
}

// Update the number of items
$_SESSION[cart][num_items] = ($old_num >$_POST[quantity]) ?
$_SESSION[cart][num_items] - ($old_num-$_POST[quantity]) :
$_SESSION[cart][num_items] + ($_POST[quantity]-$old_num);
?>



<br> 数量修改 <br>


将数量: 更改为


返回 商品列表页面.

 

功能页面,用户把购物车里面的内容保存到txt数据库,代码如下:

代码如下:

//物品数组
$master_products_list = array();


//载入物品数据函数
function LoadProducts() {
global $master_products_list;
$filename = 'products.txt';

$fp = @fopen($filename, "r")
or die("打开 $filename 文件失败");
@flock($fp, 1)
or die("锁定 $filename 文件失败");

//读取文件内容
while ($line = fgets($fp, 1024)) {
list($id, $name, $desc, $price) = explode('|', $line); //读取每行数据,数据以| 格开
$id = trim($id); //去掉首尾特殊符号
$master_products_list[$id] = array("name" => $name, //名称
"desc" => $desc, //说明
"price" => $price); //单价
}

@fclose($fp) //关闭文件
or die("关闭 $filename 文件失败");
}
?>


很简单,我们只用了4个文件就实现用php 做好购物车功能,好了这只是一款简单的php购物车代码更复杂的需要考虑更多更好.

 

希望本文所述对大家的php程序设计有所帮助。

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구