<?php
session_start();//开启session
//HTTP,无状态性
//SESSION COOKIE
SESSION:存储在服务端的,每个人存一份,可以存储任意类型的数据,默认过期时间15分钟
COOKIE:存储在客户端的,每个人存一份,只能存储字符串,默认永不过期
$_SESSION["uid"] = "zhangsan";//写入SESSION
echo $_SESSION["uid"];
setcookie("uid","zhangsan"); //设置COOKIE
?>
会话购物车,练习
login页面
<h1>登录</h1> <form action="loginchuli.php" method="post"> <div>用户名:<input type="text" name="uid" /></div> <div>密码:<input type="text" name="pwd" /></div> <div><input type="submit" value="登录" /></div> </form>
loginchuli页面
<?php session_start();----开启session include("../DBDA.php"); $db = new DBDA(); $uid = $_POST["uid"]; $pwd = $_POST["pwd"]; $sql = "select count(*) from Users where Uid='{$uid}' and Pwd = '{$pwd}'"; $r = $db->StrQuery($sql); if($r==1) { $_SESSION["uid"] = $uid; header("location:main.php"); } else { header("location:login.php"); }
main页面
<body> <?php session_start(); if(empty($_SESSION["uid"])) { header("location:login.php"); } echo $_SESSION["uid"]; ?> </body>
showlist页面
<body> <table width="100%" border="1" cellpadding="0" cellspacing="0"> <tr> <td>水果名称</td> <td>水果价格</td> <td>水果产地</td> <td>水果库存</td> <td>操作</td> </tr> <?php include("../DBDA.php"); $db = new DBDA(); $sql = "select * from fruit"; $attr = $db->Query($sql); foreach($attr as $v) { echo "<tr><td>{$v[1]}</td> <td>{$v[2]}</td> <td>{$v[3]}</td> <td>{$v[4]}</td> <td><a href='addgwc.php?code={$v[0]}'>加入购物车</a></td></tr>"; } ?> </table> <a href="gouwuche.php">查看购物车</a> </body>
addgwc页面
<?php session_start(); $code = $_GET["code"]; //如果第一次点击 if(empty($_SESSION["sg"])) { $attr = array(array($code,1)); $_SESSION["sg"] = $attr; } else { //第n次点击,n!=1 $attr = $_SESSION["sg"]; //判断该水果师是否已经存在 if(iscunzai($code)) { foreach($attr as $k=>$v) { if($v[0]==$code) { $attr[$k][1] = $v[1]+1; } } $_SESSION["sg"] = $attr; } else { $arr = array($code,1); array_push($attr,$arr); $_SESSION["sg"] = $attr; } } function iscunzai($c) { $attr = $_SESSION["sg"]; $b = false; foreach($attr as $v) { $b = $b || in_array($c,$v); } return $b; } header("location:showlist.php");
gouwuche页面
<body> <table width="100%" border="1" cellpadding="0" cellspacing="0"> <tr> <td>水果名称</td> <td>水果价格</td> <td>数量</td> </tr> <?php session_start(); include("../DBDA.php"); $db = new DBDA(); $attr = $_SESSION["sg"]; foreach($attr as $v) { $sql = "select Name,Price from fruit where Ids='{$v[0]}'"; $arr = $db->Query($sql); echo "<tr><td>{$arr[0][0]}</td> <td>{$arr[0][1]}</td> <td>{$v[1]}</td></tr>"; } ?> </table> </body>