search
HomeBackend DevelopmentPHP TutorialPHP cookie +购物车 怎么写??

现在做网站做到购物车这里我不会写了!!请高手写的代码给参考下!!谢谢了啊


回复讨论(解决方案)

那个不能放cookies的、用户下次登陆找收藏在购物车里的商品一旦没了咋办

ajax+数据库存储内容.

我也正需要购物车的资料呢,2楼所说的AJax+数据库是怎么实现的,有源码的话共享下...谢谢了!

<?php$act=$_GET[act];$product_id=$_GET[prcid];if($act=="add"){ 	$cars_id=explode(",",$_COOKIE[buypro]);	//echo "<pre class="brush:php;toolbar:false">";   	//print_r($cars_id);	//echo"
"; //exit; foreach($cars_id as $pr_id) {  if($pr_id==$product_id)  {  echo "<script>alert('您已经购买了此商品,请查看购物车!');location.href='car.php';</script>";  exit;  }    } if(empty($_COOKIE[buypro])) { setcookie("buypro",$product_id,time()+3600); setcookie("buycount","1",time()+3600); } else { $newpro=$_COOKIE[buypro].",".$product_id; $newcount=$_COOKIE[buycount].","."1"; setcookie("buypro",$newpro,time()+3600); setcookie("buycount",$newcount,time()+3600); }}//删除if($act=="del"){$buy=$_COOKIE[buypro];$cars_id=explode(",",$buy);$buycountary=explode(",",$_COOKIE[buycount]);$newid=array();$carcount=array();for($i=0;$ilocation.href='car.php';";?>

学习中

给你共享一个全套的,接点分,不够用了

//index.php<?phpinclude ("conn.php");$sql="select * from produce";//查询所有商品$rs=mysql_query($sql,$conn);//执行sql语句,得到一个结果集while($row=mysql_fetch_array($rs))//遍历结果集{?><table width="343" height="152" border="1" style="float:left">  <tr>    <td width="124" rowspan="3"><img  src="/static/imghwm/default1.png"  data-src="images/<?php echo $row["  class="lazy"pimg"]? alt="PHP cookie +购物车 怎么写??" >" width="123"    style="max-width:90%" border="0" /></td>    <td width="203" height="35">货物名称:<?php echo $row["pname"] ?></td>  </tr>  <tr>    <td height="28">货物价格:<?php echo $row["price"] ?></td>  </tr>  <tr>    <td height="27" align="center"><a href="buy.php?id=<?php echo $row["pid"] ?>&pname=<?phpecho $row["pname"] ?>">购买</a></td>  </tr>  </table><?php}?>//conn.php<?php $conn=mysql_connect("localhost","root","root"); mysql_select_db("shop",$conn); mysql_query("set names utf8");?>//car.php<?php	include_once('public.inc.php');	$arr=$_SESSION["mycar"];//从session中拿出二维数组		?>	<table width="600" height="37" border="1">		<tr>			<td width="96">商品ID</td>			<td width="154">商品数量</td>				<td width="154">商品单价</td>				<td width="154">商品总价</td>			<td width="177">删除</td>		</tr>		<?php		foreach($arr as $a)//遍历这个二维数组		{	$tp=$a["num"]*$a["price"];				$_tp += $tp;		$num += $a["num"];		?>		<tr>			<td width="96"><?php echo $a["pid"] ?></td> 			<td width="154"><?php echo $a["num"] ?></td>				<td width="154"><?php echo $a["price"] ?></td>				<td width="154"><?php echo $tp ?></td>			<td width="177"><a href="delete.php?id=<?php echo $a[pid] ?>">删除</a></td>		</tr>		<?php		}		?>	<tr>			<td width="96"> </td>			<td width="154"><?=$num?></td>				<td width="154">总价</td>				<td width="154"><?php echo $_tp ?></td>			<td width="177">s</td>		</tr>	</table>		</form>		<a href="order.php">提交订单</a>//返回到首页//buy.php<?php	include_once('public.inc.php');		ob_start();//要清空缓存就必须ob_start()		$sql="select * from qf_act where id = $_GET[id]";		$rs=mysql_query($sql);		$row=mysql_fetch_array($rs);		$price=$row["price"];		$pid=$_GET["id"];//得到购买物品的id		$arr=$_SESSION["mycar"];//将session中的变量取出来		//下面先判断这个变量是否是数组,可以得到以前是否买过东西		if(is_array($arr))		{		//如果是数组,说明以前买过东西		//如果买过东西又分两种情况:			  if(array_key_exists($pid,$arr))			  {			  // 1、array_key_exists($pid,$arr)判断$arr中是否存在键值为$pid的一个一维数组,如果存在的话,就说明此商品以前购买过,只需要把数量加1				   $uu=$arr[$pid]; //从二维数组里拿出对应的一维数组,该一维数组包括id name num 三个值				   $uu["num"]=$uu["num"]+1;  //改变数量,将数量加1				   $arr[$pid]=$uu; //改完后再将此一维数组放回二维数组中			  }			  else			  {    //2.此商品第一次购买,就将得到的id和name值组成一个一维数组				   $arr[$pid]=array("pid"=>$pid,"price"=>$price,"num"=>1);			  }		}		else		{		 		$arr[$pid]=array("pid"=>$pid,"price"=>$price,"num"=>1);		}		$_SESSION["mycar"]=$arr; //购买完后,将此数组重新放入session中,便可以在各个页面看到此session		ob_clean();//清空缓存		header("location:car.php");//跳转到购物车界面(car.php)?>


也许不是非常强大,但是做个是个基本功能都OK。根据自己的要求自己可以在修改一下

thinkPHP购物车写法代码怎么写

学习中

未登录用户购物车商品存储到cookie,已登录用户存到数据库

<?php$method=@$_POST['method'];$good_id=@$_POST['id'];$good_name=@$_POST['name'];$good_item=@$_POST['item_code'];$good_num=@$_POST['number'];$good_car_array=unserialize($_COOKIE['good_car_string']);switch($method){	case "add":		if(array_key_exists($good_id,$good_car_array))		{			echo "购物车中已经存在该商品!";		}		else		{			$good_car_array[$good_id]=array($good_item,$good_name,$good_num);			echo "添加成功";		}	break;		case "change": 		$good_car_array[$good_id][2]=$good_num;	break;		case "del":		unset($good_car_array[$good_id]);	break;	 	case "delall": 		$good_car_array="";	break;}setcookie('good_car_string',serialize($good_car_array),time()+3600*30*24);print_r($good_car_array);?>

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft