Achieve the goal: use php and mysql to write a product information management system with a shopping cart function
1. Create database and table
1. Create database and table: demodb
2. Create table: goods
Field : Product number, product name, product type, product picture, unit price, product description, inventory, add time
2. Create a php file and write the code (the following is the php file to be created and its use)
add.php Product Add page
Edit.php Product information editing form page
index.php Product information browsing page
action.php Perform operations such as adding, modifying and deleting product information
dbconfig.php Public configuration file, database connection configuration information
menu.php Website public navigation bar
uploads/ Storage directory for uploaded images
function.php Public function library file: uploading of image information, scaling and other processing functions
addCart.php Add shopping cart information operation (Put the information to be purchased into the SESSION)
myCart.php implements the browsing operation of the shopping cart information, and implements the statistics of product information (subtotal and total price)
clearCart.php implements the single product of the shopping cart information Delete or clear the shopping cart operation
UpdateCart.php Modify the number of items in the shopping cart to prevent too small constraints
Illustration of the relationship between each php file:
Okay, then here is the code part:
First of all, build Table statement:
1createdatabase newsdb;//创建库语句 2 3createtable goods ( 4 id int(10) unsigned NOTNULL AUTO_INCREMENT, 5 name varchar(64) NOTNULL, 6 typeid int(10) unsigned NOTNULL, 7 price double(6,2) unsigned NOTNULL, 8 total int(10) unsigned NOTNULL, 9 pic varchar(32) NOTNULL, 10 note text, 11 addtime int(10) unsigned NOTNULL, 12PRIMARYKEY (`id`) 13 ) //创建表语句
The following are the codes for each PHP file. Friends who need it can directly copy each code and put it in the same directory, and create uplaods in the same directory. Folder to store uploaded pictures
1 php 2//执行商品信息的增、删、改的操作 3 4//一、导入配置文件和函数库文件 5require("dbconfig.php"); 6require("function.php"); 7//二、连接MySQL,选择数据库 8$link = mysql_connect(HOST,USER,PASS) or die("数据库连接失败"); 9mysql_select_db(DBNAME,$link); 10 11 12//三、获取action参数的值,并做对应的操作 13switch($_GET["action"]) 14 { 15case "add": //添加 16 //1.获取添加信息 17$name = $_POST["name"]; 18$typeid = $_POST["typeid"]; 19$price = $_POST["price"]; 20$total = $_POST["total"]; 21$note = $_POST["note"]; 22$addtime = time(); 23//2.验证()省略 24if(empty($name)) 25 { 26die("商品名称必须有值"); 27 } 28//3.执行图片上传 29$upinfo = uploadFile("pic","./uploads/"); 30if($upinfo["error"]===false) 31 { 32die("图片信息上传失败:".$upinfo["info"]); 33 }else 34 { 35//上传成功 36$pic = $upinfo["info"];//获取上传成功的图片名 37 38 } 39//4.执行图片缩放 40 imageUpdateSize('./uploads/'.$pic,50,50); 41//5.拼装sql语句,并执行添加 42$sql = "insert into goods values(null,'{$name}','{$typeid}',{$price},{$total},'{$pic}','{$note}',{$addtime})"; 43mysql_query($sql,$link); 44//6.判断并输出结果 45if(mysql_insert_id($link)>0) 46 { 47echo "商品发布成功"; 48 }else 49 { 50echo "商品发布失败"; 51 } 52echo "
查看商品信息"; 53 54break; 55case "del": //删除 56 //获取要删除的id号并拼装删除sql,执行 57$sql = "delete from goods where id={$_GET['id']}"; 58 59mysql_query($sql,$link); 60//执行图片删除 61if(mysql_affected_rows($link)>0) 62 { 63 @unlink("./uploads/".$_GET['picname']); 64 @unlink("./uploads/s_".$_GET['picname']); 65 } 66//跳转到浏览界面 67header("Location:index.php"); 68break; 69 70case "update": //修改 71 //1.获取要修改的信息 72$name = $_POST["name"]; 73$typeid = $_POST["typeid"]; 74$price = $_POST["price"]; 75$total = $_POST["total"]; 76$note = $_POST["note"]; 77$id = $_POST['id']; 78$pic = $_POST['oldpic']; 79//2.数据验证 80if(empty($name)) 81 { 82die("商品名称必须有值"); 83 } 84//3.判断有无图片上传 85if($_FILES['pic']['error']!=4) 86 { 87//执行上传 88$upinfo = uploadFile("pic","./uploads/"); 89if($upinfo["error"]===false) 90 { 91die("图片信息上传失败:".$upinfo["info"]); 92 }else 93 { 94//上传成功 95$pic = $upinfo["info"];//获取上传成功的图片名 96 //4.有图片上传执行缩放 97 imageUpdateSize('./uploads/'.$pic,50,50); 98 } 99 } 100101102//5.执行修改103$sql = "update goods set name='{$name}',typeid={$typeid},price={$price},total={$total},note='{$note}',pic='{$pic}' where id={$id}"; 104mysql_query($sql,$link); 105//6.判断是否修改成功106if(mysql_affected_rows($link)>0) 107 { 108if($_FILES['pic']['error']!=4) 109 { 110//若有图片上传,就删除老图片111 @unlink("./uploads/".$_POST['oldpic']); 112 @unlink("./uploads/s_".$_POST['oldpic']); 113 } 114echo "修改成功"; 115 }else116 { 117echo "修改失败".mysql_error(); 118 } 119echo "
查看商品信息"; 120break; 121default: 122echo "错误";break; 123124 } 125//四、关闭数据库126mysql_close($link);
1 php 2//公共信息配置文件 3 4//数据库信息配置 5define("HOST","localhost");//主机名 6define("USER","root"); //用户名 7define("PASS","root"); //密码 8define("DBNAME","demodb"); //数据库名 910//商品类型列表信息11$typelist=array(1=>"服装",2=>"数码",3=>"食品"); 121314 ?>
1 2 3商品信息管理 4 5 67 include("menu.php");//导入导航栏 ?> 8 53 54浏览商品信息
910
11
5212 20 php 21//从数据库中读取信息并输出到浏览器表格中 22 //1.导入配置文件23require("dbconfig.php"); 24//2.连接数据库,并选择数据库25$link = @mysql_connect(HOST,USER,PASS) or die("数据库连接失败"); 26mysql_select_db(DBNAME,$link); 27//3.执行商品信息查询28$sql="select * from goods"; 29$result = mysql_query($sql,$link); 3031//4.解析商品信息(解析结果集)32while($row = mysql_fetch_assoc($result)) 33 { 34echo "商品编号 13商品名称 14商品图片 15单价 16库存量 17添加时间 18操作 19"; 35echo " "; 48 } 49//5.释放结果集,关闭数据库50 ?> 51{$row["id"]} "; 36echo "{$row["name"]} "; 37echo ""; 38echo " {$row["price"]} "; 39echo "{$row["total"]} "; 40echo "".date("Y-m-d H:i:s",$row['addtime'])." "; 41echo "42 $row['pic']}'>删除 43 修改 44 放入购物车 4546 "; 47echo "
1 2 3商品信息管理 4 5 67 php 8include("menu.php");//导入导航栏 9 //1.导入配置文件10require("dbconfig.php"); 11//2.连接数据库,并选择数据库12$link = @mysql_connect(HOST,USER,PASS) or die("数据库连接失败"); 13mysql_select_db(DBNAME,$link); 14//3.获取要修改的商品信息15$sql="select *from goods where id={$_GET['id']}"; 16$result = mysql_query($sql,$link); 17//4.判断是否获取到要编辑的商品信息18if($result&&mysql_num_rows($result)>0) 19 { 20$shop=mysql_fetch_assoc($result);//解析出要修改的商品信息21 }else22 { 23die("没有找到要修改的商品信息"); 24 } 2526 ?> 27 82 83编辑商品信息
28 81
1 php 2//公共函数库 3 4/* 5 * 文件上传处理函数 6 * @param string filename 要上传的文件表单项名 7 * @param string $path 上传文件的保存路径 8 * @param array 允许的文件类型 9 * @return array 两个单元: ["error"] false:失败,ture:成功 10 * ["info"] 存放失败原因或成功的文件名 11*/ 12 13function uploadFile($filename,$path,$typelist=null) 14{ 15//1.获取上传文件的名字 16$upfile = $_FILES[$filename]; 17if(empty($typelist)) 18 { 19$typelist=array("image/gif","image/jpg","image/jpeg","image/png","image/pjpeg","image/x-png");//允许的文件类型 20 } 21$res=array("error"=>false);//存放返回的结果 22 //2.过滤上传文件的错误号 23if($upfile["error"]>0) 24 { 25switch($upfile["error"]) 26 { 27case 1: 28$res["info"]="上传的文件超过了 php.ini中upload_max_filesize选项大小"; 29break; 30case 2: 31$res["info"]="上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项"; 32break; 33case 3: 34$res["info"]="文件只有部分被上传"; 35break; 36case 4: 37$res["info"]="没有文件被上传"; 38break; 39case 6: 40$res["info"]="找不到临时文件夹"; 41break; 42case 7: 43$res["info"]="文件写入失败"; 44break; 45default: 46$res["info"]="未知错误!"; 47break; 48 49 } 50return$res; 51 } 52//3.本次文件大小的限制 53if($upfile["size"]>1000000) 54 { 55$res["info"]="上传文件过大!"; 56return$res; 57 } 58//4.过滤类型 59if(!in_array($upfile["type"],$typelist)) 60 { 61$res["info"]="上传类型不符!".$upfile["type"]; 62return$res; 63 } 64//5.初始化下信息(为图片产生一个随机的名字) 65$fileinfo = pathinfo($upfile["name"]); 66do 67 { 68$newfile = date("YmdHis").rand(1000,9999).".".$fileinfo["extension"];//随机产生名字 69 70 }while(file_exists($newfile)); 71//6.执行上传处理 72if(is_uploaded_file($upfile["tmp_name"])) 73 { 74if(move_uploaded_file($upfile["tmp_name"],$path."/".$newfile)) 75 { 76//将上传成功后的文件名赋给返回数组 77$res["info"]=$newfile; 78$res["error"]=true; 79return$res; 80 }else 81 { 82$res["info"]="上传文件失败!"; 83 } 84 }else 85 { 86$res["info"]="不是一个上传的文件"; 87 } 88return$res; 89} 90//================================================== 91/* 92 * 93 * 等比缩放函数(以保存的方式实现) 94 * @param string $picname 被缩放的处理图片源 95 * @param int $maxx 缩放后的图片的最大宽度 96 * @param int $maxy 缩放后图片的最大高度 97 * @param string $pre 缩放后图片名的前缀名 98 * @param string 返回后的图片名称(带路径),如a.jpg=>s_a.jpg 99*/100function imageUpdateSize($picname,$maxx=100,$maxy=100,$pre="s_"){ 101$info=getimagesize($picname); //获取图片的基本信息102$w = $info[0];//获取宽度103$h = $info[1]; // 获取高度104switch($info[2]){ 105case 1: //gif106$im=imagecreatefromgif($picname); 107break; 108case 2: //jpg109$im=imagecreatefromjpeg($picname); 110break; 111case 3: //png112$im=imagecreatefrompng($picname); 113break; 114default : 115die("图片类型错误"); 116 } 117//计算缩放比例118if(($maxx/$w)>($maxy/$h)){ 119$b=$maxy/$h; 120 }else{ 121$b=$maxx/$w; 122 } 123//计算缩放后的尺寸124$nw=floor($w*$b); 125$nh=floor($h*$b); 126//创建一个新的图像源127$nim=imagecreatetruecolor($nw,$nh); 128//执行等比缩放129 imagecopyresampled($nim,$im,0,0,0,0,$nw,$nh,$w,$h); 130//输出图像131$picinfo=pathinfo($picname); 132$newpicname=$picinfo["dirname"]."/".$pre.$picinfo["basename"]; 133134switch($info[2]){ 135case 1: 136 imagegif($nim,$newpicname); 137break; 138case 2: 139 imagejpeg($nim,$newpicname); 140break; 141case 3: 142 imagepng($nim,$newpicname); 143break; 144default: 145echo "图片压缩错误"; 146 } 147//释放图片资源148 imagedestroy($im); 149 imagedestroy($nim); 150//返回结果151return$newpicname; 152 }
1 php 2session_start();//启动会话 3 4 ?> 5 6 7商品信息管理 8 9 1011 include("menu.php");//导入导航栏 ?>12 48 49添加商品到购物车
1314 php 15//从数据库中读取要购买的信息并添加到购物车中 16 //1.导入配置文件17require("dbconfig.php"); 18//2.连接数据库,并选择数据库19$link = @mysql_connect(HOST,USER,PASS) or die("数据库连接失败"); 20mysql_select_db(DBNAME,$link); 21//3.执行商品信息查询(获取要购买的信息)22$sql="select * from goods where id={$_GET['id']}"; 23$result = mysql_query($sql,$link); 2425//4.判断是否没有找到要购买的信息,若有就读取出要购买的信息26if(empty($result) || mysql_num_rows($result)==0) 27 { 28die("没有找到要购买的信息!"); 29 }else30 { 31$shop = mysql_fetch_assoc($result); 32 } 33$shop["num"]=1;//添加一个数量的字段 34 //5.放入购物车中(若已存在的商品实现数量累加)35if(isset($_SESSION["shoplist"]{$shop['id']})) 36 { 37//若存在数量增加138$_SESSION["shoplist"][$shop['id']]["num"]++; 39 }else40 { 41//若不存在,作为新购买的商品添加到购物车中42$_SESSION["shoplist"][$shop['id']]=$shop; 43 } 4445 ?> 46 47
1 php 2session_start();//启动会话 3 4 ?> 5 6 7商品信息管理 8 9 1011 include("menu.php");//导入导航栏 ?>12 52 53浏览我的购物车
13
14
5115 23 php 24$sum =0;//定义总金额的变量25if(isset($_SESSION["shoplist"])){ 26foreach($_SESSION["shoplist"] as$v) 27 { 28echo "商品id号 16商品名称 17商品图片 18单价 19数量 20小计 21操作 22"; 29echo " "; 41$sum+=$v["price"]*$v['num'];//累计金额42 } 43 } 44 ?> 45{$v['id']} "; 30echo "{$v['name']} "; 31echo ""; 32echo " {$v['price']} "; 33echo "34 35 {$v['num']} 36 37 "; 38echo "".($v["price"]*$v['num'])." "; 39echo "删除 "; 40echo "46 50总计金额: 47echo$sum; ?> 4849
1 php 2 3//删除购物车session中的信息 4session_start();//启动会话 5 6 //判断是删除一个商品还是清空购物车 7if($_GET['id']) 8 { 9//只删除一种商品10unset($_SESSION['shoplist'][$_GET['id']]); 11 }else12 { 13//清空session中的商品14unset($_SESSION["shoplist"]); 15 } 161718//跳转到浏览购物车界面19header("Location:myCart.php"); 20 ?>
1 php 2session_start();//启动会话 3 //修改购物车中的信息 4 5 //获取要修改的信息 6 7$id = $_GET['id']; 8$num = $_GET['num']; 910//修改商品信息11$_SESSION["shoplist"][$id]["num"]+=$num; 1213//防止商品数量过小14if($_SESSION["shoplist"][$id]["num"]<1) 15 { 16$_SESSION["shoplist"][$id]["num"]=1; 17 } 18//跳转回我的购物车界面19header("Location:myCart.php"); 2021 ?>
The following is a screenshot of index.php:
myCart .php screenshot:
The last sentence: Hahahahahahahahahahahahahahahaha! ! ! !
The above introduces the basic example of PHP: Product Information Management System v11, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.