提供一个最简单的购物车

发表于:2007-07-04来源:作者:点击数: 标签:
1、session_start()为什么不写在类里面? 答: 如果在类中session_start();那么当程序中再次出现session_start()时会出错 2、不要再每次增加商品和修改数量的时候计算金额,只存数量和单价就可以了,需要金额的时候再计算比较好点 答:好在这只是数组操作,应该

1、session_start()为什么不写在类里面?
答: 如果在类中session_start();那么当程序中再次出现session_start()时会出错
2、不要再每次增加商品和修改数量的时候计算金额,只存数量和单价就可以了,需要金额的时候再计算比较好点
答:好在这只是数组操作,应该对效率影响不大,所以我还是参照现在网上商店的作法,给出计算结果
3、为什么把价格取整?
答:这的确是一个重大失误,价格不能intval而应floatval.

以下把修改后的文件再发一次.
cart.class.php

已经修改后的PHP代码:------------------------------------------------------------------

<?php
/**
*  类名: cart
*  描述: 尝试以最简单的方式实现购物车
*  其他: 2004-8-19
*/
class cart
{
    /**
    *   函数名称:   addItem
    *   函数功能:   添加商品
    *   输入参数:   $data ------------- 商品数组
    *   函数返回值: none
    *   其它说明:   因为数据是记录在session中,所以不用返回
    */
    function addItem($data)
    {
        if(is_array($data)&&!empty($data))
        {
            foreach($data as $key=>$val)
            {
                // 如果商品存在就加数量和价格
                if($this->_isExists($key))
                {
                    $_SESSION['cart'][$key]["count"] += floatval($val['price'])*intval($val['num']);
                    $_SESSION['cart'][$key]["num"]   += intval($val['num']);
                }
                // 否则直接加入
                else
                {
                    $_SESSION['cart'][$key]  = $data[$key];
                    $_SESSION['cart'][$key]["name"]  = $val['name'];
                    $_SESSION['cart'][$key]["price"] = $val['price'];
                    $_SESSION['cart'][$key]["count"] = floatval($val['price'])*intval($val['num']);
                    $_SESSION['cart'][$key]["num"]   = intval($val['num']);
                }
            }
        }
    }
 
    /**
    *   函数名称:   _isExists
    *   函数功能:   判断此商品是否存在
    *   输入参数:   $id ---------- 商品ID
    *   函数返回值: bool
    *   其他说明:   2004-8-19
    */
    function _isExists($id)
    {
        if(isset($_SESSION['cart'][$id])&&!empty($_SESSION['cart'][$id])&&array_key_exists($id,$_SESSION['cart']))
        {
            Return true;
        }
        else
        {
            Return false;
        }
    }
 
    /**
    *   函数名称:   modItem
    *   函数功能:   修改商品数量
    *   输入参数:   $id -------------- 商品ID
    *              $num ------------- 商品数量
    *   函数返回值: 返回值说明
    *   其他说明:   说明
    */
    function modItem($id,$num)
    {
        $arr = $this->getItems($id);
        // 如果商品存在就改数量和价格
        if($this->_isExists($id))
        {
            $_SESSION['cart'][$id]["count"] = intval($arr['price'])*intval($num);
            $_SESSION['cart'][$id]["num"]   = intval($num);
        }
    }
 
    /**
    *   函数名称:   getItems
    *   函数功能:   取得商品数组
    *   输入参数:   $id --------------- 某商品的ID
    *   函数返回值: array
    *   其它说明:   2004-8-19
    */
    function getItems($id=null)
    {
        if(isset($_SESSION['cart']))
        {
            if($id==null)
            {
                Return $_SESSION['cart'];
            }
            else
            {
                Return $_SESSION['cart'][$id];
            }
        }
    }
 
    /**
    *   函数名称:   emptyItem
    *   函数功能:   删除商品
    *   输入参数:   $id ----------- 商品ID
    *   函数返回值: bool
    *   其它说明:   2004-8-19
    */
    function emptyItem($id=null)
    {
        if($id==null)
        {
            unset($_SESSION['cart']);
        }
        else
        {
            unset($_SESSION['cart'][$id]);
        }
    }
 
    /**
    *   函数名称:   sum
    *   函数功能:   统计总价
    *   输入参数:   none
    *   函数返回值: int
    *   其它说明:   2004-8-19
    */
    function sum()
    {
        $total = 0;
        if(isset($_SESSION['cart'])&&!empty($_SESSION['cart']))
        {
            foreach($_SESSION['cart'] as $key=>$val)
            {
                $total += $val['count'];
            }
        }
        Return $total;
    }
}
?>

 

--------------------------------------------------------------------------------

测试文件,发现以前的办法太笨了。

PHP代码:--------------------------------------------------------------------------------

<?php
/**************************************************************************
    Copyright (C), 2004, ustb
    文件名: testcart.php
    作  者: [偶然]
    说  明: 测试购物车
  版  本: 1.0
    日  期: 2004-8-19
    历  史:
        <作者>          <时间>          <版本>       <说明>
        [偶然]         2004-8-19        1.0         创建模块
**************************************************************************/
session_start();
require_once "cart.class.php";
$cart = new cart();
 
// 添加
if(isset($_POST['action'])&&!empty($_POST['action'])&&$_POST['action']=="additem")
{
    $postitempid   = isset($_POST['itempid'])&&!empty($_POST['itempid'])?$_POST['itempid']:null;
    $postitemname  = isset($_POST['itemname'])&&!empty($_POST['itemname'])?$_POST['itemname']:null;
    $postitemprice = isset($_POST['itemprice'])&&!empty($_POST['itemprice'])?$_POST['itemprice']:null;
    $postitemnum = isset($_POST['itemnum'])&&!empty($_POST['itemnum'])?$_POST['itemnum']:null;
    $arr = array(
        "$postitempid" =>array(
            "name"  => $postitemname,
            "price" => $postitemprice,
            "num"   => $postitemnum
        )
    );
    $cart->addItem($arr);
}
 
 
// 删除
if(isset($_GET['act'])&&!empty($_GET['act'])&&$_GET['act']=="del"&&!empty($_GET['id']))
{
    $cart->emptyItem($_GET['id']);
}
// 清空
if(isset($_GET['act'])&&!empty($_GET['act'])&&$_GET['act']=="clean")
{
    $cart->emptyAll();
    header("location: testcart.php");
}
 
// 改
if(isset($_POST['action'])&&$_POST['action']=="修改")
{
 //print_r($_POST);
    $postpnum  = isset($_POST['pnum'])&&!empty($_POST['pnum'])?$_POST['pnum']:null;
    if(!empty($postpnum))
    {
        foreach($postpnum as $key=>$val)
        {
            $cart->modItem($key,$val[0]) ;
        }
    }
}
?>
<a href="?act=clean">清空</a>
<table border=1 width="700" align="center">
<form name="form_cart" method="post" action="">
<?php
// 取得
$getarr = $cart->getItems();
if(is_array($getarr)&&!empty($getarr))
{
    // 列表
    foreach($getarr as $pkey=>$pval)
    {
        if($pkey!=null)
        {
?>
<tr>
    <td>ID:<?
=$pkey?></td>
    <td>名称:<?
=$pval['name']?></td>
    <td>单价:<?
=$pval['price']?></td>

    <td>数量:<input type="text" name="pnum[<?
=$pkey?>][]" value="<?
=$pval['num']?>"></td>
    <td>合计<?
=$pval['count']?></td>
    <td><a href="?act=del&id=<?
=$pkey?>">删除</a></td>
</tr>
<?php
        }
    }
}
?>

<tr>
<td colspan="6"><input type="submit" name="action" value="修改">总计:<?
=$cart->sum()?></td>
</tr>
</form>
</table>
因为只做测试,所以不对数量,ID等参数做严格限制,爱填什么就填什么.
<form name="form_add" method=post action="">
ID:<input type="text" name="itempid">
名称:<input type="text" name="itemname">
单价:<input type="text" name="itemprice">
数量:<input type="text" name="itemnum" value="">
<input type="hidden" name="action" value="additem">
<input type="submit">
</form>

 

 

 

 

另一个购物车

PHP代码:--------------------------------------------------------------------------------
我的购物车 因为是给公司写的程序而且随用什么功能家什么功能
所以我连购物车的模板都放进来了,那个时候还不会用模板
里面有的函数 是根据我的实际需要制定的 请仅参考实际购物车部分

Class Car extends Mysql
{
    #添加
    Function AddCar($id)
    {
        $num=1;
        $new=array("id"=>$id,"num"=>$num,"danjia"=>"","beizhu"=>"");
        if(!is_array($_SESSION[car]))
        {
            $_SESSION[car]=array();
        }
        while (list($tmp)=each($_SESSION[car])) //如果购物车内有所添加的产品则提示有
        {
             if(strcmp($_SESSION[car][$tmp][id],$id)==0)
             {
                 return("have");
                 exit;
             }
        }

        if(array_push($_SESSION[car],$new))
        {
            return("ok");
            exit;
        }
        else
        {
            return("error");
            exit;
        }
    }

    #删除
    Function DelCar($id)
    {
        while (list ($tmp)=each($_SESSION[car]))
        {
            if(strcmp($_SESSION[car][$tmp][id],$id)==0)
            {
                unset($_SESSION[car][$tmp]);
                reset($_SESSION[car]);
                return("ok");
             }
        }
    }

    #清空
    Function DelAll()
    {
        session_unregister(car);
        return("ok");
    }

    #改变
    Function EditNum($id,$num,$danjia,$beizhu)
    {
        if($num<1)
        {
            $num=1;
        }
        $a=0;
        $coun=count($num);
        while($a<$coun)
        {
            while (list($ids)=each($_SESSION[car]))
            {
                if(strcmp($_SESSION[car][$ids][id],$id[$a])==0)
                {
                     $_SESSION[car][$ids][num]=$num[$a];
                     $_SESSION[car][$ids][danjia]=$danjia[$a];
                     $_SESSION[car][$ids][beizhu]=$beizhu[$a];
                    
                }
                $a++;
            }
       
        }
        reset($_SESSION[car]);
        return("ok");
    }

    #列出购物车
    Function ListCar()
    {
        parent::Connects();
        if(isset($_SESSION[add_baojia_chan]) or !empty($_SESSION[add_baojia_chan]))
        {
            $action="MakeBaojiaDan.php?action=add_chan";
            $strzb="checked";
        }
        else
        {
            $action="MakeBaojiaDan.php";
            $strb="checked";
        }
        if(isset($_SESSION[add_hetong_chan]) or !empty($_SESSION[add_hetong_chan]))
        {
            $action="MakeHeTongDan.php?action=add_chan";
            $strzh="checked";
        }
        if(isset($_SESSION[add_chuku_chan]) or !empty($_SESSION[add_chuku_chan]))
        {
            $strzc="checked";
        }
        else
        {
            $action="MakeBaojiaDan.php";
            $strb="checked";
        }
        if(!isset($_SESSION[car]) or empty($_SESSION[car]))
        {
            $html=<<<EOT
<html>

<head>
<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=??????">
<title>已添加产品</title>
<link rel="stylesheet" type="text/css" href="Include/css.css">
</head>

<body>

<table border="0" cellpadding="0" cellspacing="0" width="500" id="table1">
    <tr>
        <td height="25" bgcolor="#F3F3F3" width="100">
        <p align="center">名称</td>
        <td height="25" bgcolor="#F3F3F3" width="100">
        <p align="center">型号</td>
        <td height="25" bgcolor="#F3F3F3" width="80" align="center">
        <p align="center">单价</td>
        <td height="25" bgcolor="#F3F3F3" width="50" align="center">数量</td>
        <td height="25" bgcolor="#F3F3F3" width="80" align="center">总价格</td>
        <td height="25" bgcolor="#F3F3F3" width="90" align="center">操作</td>
    </tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="500" id="table2">
    <tr><form method="POST" action="Car.php?action=Edit">
        <td height="50" style="border-right: 1px solid #C0C0C0; border-top: 1px solid #C0C0C0; border-bottom: 1px solid #C0C0C0" width="500" align="center"> 
        还没有选定任何产品</td>
        </tr></form>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="500" id="table3">
    <tr>
        <td bgcolor="#F3F3F3" height="30">
        <p align="center"><a href="" onClick="window.close();window.opener.location.reload()">返回选择产品</a></td>
    </tr>
</table>

</body>

</html>
EOT;
            return($html);
            exit;
        }
        $count=count($_SESSION[car]);
        $i=0;
        $html=<<<EOT
<html>

<head>
<meta http-equiv='Content-Language' content='zh-cn'>
<meta http-equiv='Content-Type' content='text/html; charset=??????'>
<title>已添加产品</title>
<link rel='stylesheet' type='text/css' href='Include/css.css'>
<SCRIPT language=javascript>
function SubmitTo(formname)
{
    if(formname.sheng["0"].checked)
    {
        url='MakeBaojiaDan.php';
    }
    if(formname.sheng["1"].checked)
    {
        url='MakeHeTongDan.php?action=allmake';
    }
    if(formname.sheng["2"].checked)
    {
        url='MakeChuKuDan.php?action=allmake';
    }
    if(formname.sheng["3"].checked)
    {
        url='MakeBaojiaDan.php?action=add_chan';
    }
    if(formname.sheng["4"].checked)
    {
        url='MakeHeTongDan.php?action=add_chan';
    }
    if(formname.sheng["5"].checked)
    {
        url='MakeChuKuDan.php?action=add_chan';
    }
   
    formname.action = url;
}
</SCRIPT>
</head>

<body>

<table border='0' cellpadding='0' cellspacing='0' width='700' id='table1'>
    <tr><form method='POST' action='Car.php?action=Edit' name="edit">
        <td height='25' bgcolor='#F3F3F3' width='100'>
        <p align='center'>名称</td>
        <td height='25' bgcolor='#F3F3F3' width='100'>
        <p align='center'>型号</td>
        <td height='25' bgcolor='#F3F3F3' width='100' align='center'>
        <p align='center'>单价</td>
        <td height='25' bgcolor='#F3F3F3' width='50' align='center'>数量</td>
        <td height='25' bgcolor='#F3F3F3' width='70' align='center'>总价格</td>
        <td height='25' bgcolor='#F3F3F3' width='180' align='center'>备注</td>
        <td height='25' bgcolor='#F3F3F3' width='100' align='center'>操作</td>
    </tr>
</table>
EOT;

        while($i<=$count){
        while (list($tmp)=each($_SESSION[car])) //如果购物车内有所添加的产品则数量自动增加
        {
            $id[$i]=$_SESSION[car][$tmp][id];
            $num[$i]=$_SESSION[car][$tmp][num];
            $danjia[$i]=$_SESSION[car][$tmp][danjia];
            $beizhu[$i]=$_SESSION[car][$tmp][beizhu];
            $this->Get($id[$i]);
            if(empty($_SESSION[car][$tmp][danjia]))
            {
                $danjia[$i]=$this->maijia;
            }
            $zongjia=$num[$i]*$danjia[$i];

            $html.="<table border='0' cellpadding='0' cellspacing='0' width='700' id='table2'><tr>";
            $html.="<td height='50' style='border-right: 1px solid #C0C0C0; border-top: 1px solid #C0C0C0; border-bottom: 1px solid #C0C0C0' width='100' align='center'>".$this->name."</td>";
            $html.="<td height='50' style='border-right: 1px solid #C0C0C0; border-top: 1px solid #C0C0C0; border-bottom: 1px solid #C0C0C0' width='100' align='center'>".$this->xinghao."</td>";
            $html.="<td height='50' style='border-right: 1px solid #C0C0C0; border-top: 1px solid #C0C0C0; border-bottom: 1px solid #C0C0C0' width='100' align='center'><input type='text' name='danjia[]' size='5' style='font-size: 9pt; color: #FF0000; text-align: center; border: 1px solid #000000' value='".$danjia[$i]."'></td>";
            $html.="<td height='50' style='border-right: 1px solid #C0C0C0; border-top: 1px solid #C0C0C0; border-bottom: 1px solid #C0C0C0' width='50' align='center'><input type='text' name='num[]' size='5' style='font-size: 9pt; color: #FF0000; text-align: center; border: 1px solid #000000' value='".$num[$i]."'></td>";
            $html.="<td height='50' style='border-right: 1px solid #C0C0C0; border-top: 1px solid #C0C0C0; border-bottom: 1px solid #C0C0C0' width='70' align='center'>".$zongjia."</td>";
            $html.="<td height='50' style='border-right: 1px solid #C0C0C0; border-top: 1px solid #C0C0C0; border-bottom: 1px solid #C0C0C0' width='180' align='center'><textarea rows='2' name='beizhu[]' cols='22'>".$beizhu[$i]."</textarea></td>";
            $html.="<td height='50' style='line-height: 150%; border-top: 1px solid #C0C0C0; border-bottom: 1px solid #C0C0C0' width='100' align='center'><a href='Car.php?action=Del&id=".$id[$i]."'>删除</a></td><input type='hidden' name='id[]' value='".$_SESSION[car][$tmp][id]."'></tr></table>";

            $heji+=$zongjia;
        }
        $i++;
        }
        $_SESSION[Car_heji]=$heji;
        $html.=<<<EOT
<table border="0" cellpadding="0" cellspacing="0" width="700" id="table3">
    <tr>
        <td height='30' width="700" colspan="2">
        <p align="center">合计 $heji 元</td>
    </tr>
    <tr>
        <td bgcolor="#F3F3F3" height="30" width="700" colspan="2">
        <p align="center"><input type="submit" value="确认修改" name="B1"></td>
    </tr></form>
    <tr><form method="POST" action='' onsubmit="return SubmitTo(this)" name="add" id="add">
        <td height="150" style="border-top: 1px solid #C0C0C0; border-bottom: 1px solid #C0C0C0" width="89">
       
            <p align="center"> </p>
            <p align="center"> </p></td>
        <td height="200" style="border-top: 1px solid #C0C0C0; border-bottom: 1px solid #C0C0C0" width="611">
       
            付款方式:<input type="radio" value="1" name="fukuan">款到发货&nbsp;&nbsp;
            <input type="radio" value="2" name="fukuan">邮局汇款&nbsp;&nbsp;
            <input type="radio" value="3" name="fukuan">银行汇款&nbsp;
            <input type="radio" value="4" name="fukuan">支票&nbsp;
            <input type="radio" value="5" name="fukuan" checked>现金<p>送货方式:<input type="radio" value="1" name="fahuo" checked>送货上门&nbsp;&nbsp;
            <input type="radio" value="2" name="fahuo">普通邮寄&nbsp;&nbsp;
            <input type="radio" value="3" name="fahuo">中铁快运&nbsp;&nbsp;
            <input type="radio" value="4" name="fahuo">空运&nbsp;&nbsp;
            <input type="radio" value="5" name="fahuo">EMS特快专递&nbsp;&nbsp;
            <input type="radio" value="6" name="fahuo">客户上门提货</p>
            <p>发票选项:<input type="radio" value="1" name="fapiao" checked>增值发票&nbsp;&nbsp;
            <input type="radio" value="2" name="fapiao">普通发票&nbsp;&nbsp;
            <input type="radio" value="3" name="fapiao">不要发票</p>
            <p>备注:<textarea rows="4" name="beizhu" cols="38"></textarea></p></td>
    </tr>
    <tr>
        <td bgcolor="#F3F3F3" height="30" width="700" colspan="2">
        <INPUT name=shengs type=hidden value=0>
        <p align="center">
        <input type="radio" name="sheng" value="1" $strb>直接生成报价单&nbsp;
        <input type="radio" name="sheng" value="2" $strh>直接转成合同&nbsp;&nbsp;
        <input type="radio" name="sheng" value="3" $strc>直接生成出库单&nbsp;
        <input type="radio" name="sheng" value="4" $strzb>追加报价单&nbsp;
        <input type="radio" name="sheng" value="5" $strzh>追加合同单
        <input type="radio" name="sheng" value="6" $strzc>追加出库单</td>
    </tr>
    <tr>
        <td bgcolor="#F3F3F3" height="30" width="700" colspan="2">
        <p align="center"><a href="Car.php?action=Delall">清空</a> |
        <input type="submit" value="确认生成" name="Submit"> | <a href="Index.php?s=chanpin" onClick="window.close();">继续选择产品</a></td>
    </tr></form>
</table>

</body>

</html>
EOT;
return($html);
    }

    #读取基本资料
    var $name;
    var $xinghao;
    var $maijia;
    Function Get($id)
    {
        parent::Connects();
        $sql="SELECT * FROM chanpin WHERE ID='$id'";
        $query=mysql_query($sql);
        $row=mysql_fetch_array($query);
        $this->name=$row['name'];
        $this->xinghao=$row['xinghao'];
        $this->maijia=$row['maijia'];
    }

 


}

--------------------------------------------------------------------------------

原文转自:http://www.ltesting.net