PHP作业,cookie实现保存浏览历史,代码、运行截图、注释

1.练习cookie的基本用法,理解cookie的工作原理。

2.设计一个商品列表页面(数据从数据库读取),单击每个商品时,在新页面显示商品详情。

通过cookie实现保存商品浏览历史,并显示在商品详情页的下方,浏览历史最多保存3条。【提交代码截图和效果截图】

使用的sql文件:productinfo
使用的图片文件:images.zip
请自行下载

<?php
$link = mysqli_connect('localhost', 'root', 'root', 'productinfo', 3306);
$sql = "select * from productinfo";
$res = mysqli_query($link, $sql);
//显示商品列表
echo "<ul>";
//$row 保存一行, assoc函数 返回一个数组,数组的索引值是键名
while($row = mysqli_fetch_assoc($res)){

   echo "<img src='{$row['productPic']}'>";

   echo"<li><a href='product.php?id={$row['productID']}'>{$row['productName']}</a></li>";
}
echo "</ul>";

mysqli_close($link);
?>

在这里插入图片描述

<?php
$link = mysqli_connect('localhost', 'root', 'zwq123', 'zuoye');
//获取点击事件
$id=$_GET["id"];

//查询指定商品
$sql = "select * from productinfo where productID = $id";
$res = mysqli_query($link,$sql);
$pro = mysqli_fetch_assoc($res);

//用cookie 获取浏览历史
//json_decode 对json字符串进行解码,第二个参数为true时返回数组,为false时返回对象
$history=isset($_COOKIE['product_history']) ? json_decode($_COOKIE['product_history'],true) : array();

//将当前商品保存到浏览历史中,最多保存三条
//id的值是否在history数组中,若没有则进入if
if(!in_array($id,$history)){
   $history[] = $id;
   if(count($history)>3){
       //shift 与 pop 一样
       array_shift($history);
   }
   //json_encode  把字符转换为一串数字
   // 设置cookie  cookie名     json 编码             存活时间
   setcookie('product_history',json_encode($history),time()+3600*24);
}

//显示商品
echo "<h1>{$pro['productName']}</h1>";
echo "<img src='{$pro['productPic']}'>";
echo "<p>{$pro['productIntro']}</p>";
//显示浏览历史
if(!empty($history)){
   echo "<h2>浏览历史如下</h2>";
   echo"<ul>";
   foreach($history as $p){
       $sql = "select productName from productinfo where productID = $p";

       $res = mysqli_query($link, $sql);
       $row = mysqli_fetch_row($res)[0];
    //   $row = mysqli_fetch_assoc($res);
    //   echo"<li><a href='product.php?id={$p}'>{$row['productName']}</a></li>";
       echo"<li><a href='conn.php?id={$p}'>$row</a></li>";

   }

   echo "</ul>";
}
mysqli_close($link);
?>

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值