search
HomeBackend DevelopmentPHP TutorialPHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial

PHP basic example: product information management system v1.1, information management system v1.1

Achieve the goal: use php and mysql to write a product information management system with Shopping cart function

1. Create database and tables

 1. Create database and tables: demodb

2. Create a table: goods

Fields: product number, product name, product type, product picture, unit price, product description, inventory, adding time

2. Create the php file and write the code (the following is the php file to be created and its purpose)

add.php Product addition 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 operation of adding shopping cart information (putting purchase information into SESSION)

MyCart.php implements the browsing operation of shopping cart information, and implements the statistics of product information (subtotal and total price)

ClearCart.php implements the operation of deleting a single product or clearing the shopping cart of shopping cart information

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, here is the code part:

The first is the table creation statement:

PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial 1 create database newsdb;//Create library statement 2 3 create table goods ( 4 id int(10) unsigned NOT NULL AUTO_INCREMENT, 5 name varchar(64) NOT NULL, 6 typeid int(10) unsigned NOT NULL, 7 price double(6,2) unsigned NOT NULL , 8 total int(10) unsigned NOT NULL, 9 pic varchar(32) NOT NULL, 10 note text, 11 addtime int(10) unsigned NOT NULL, 12 PRIMARY KEY (`id`) 13 ) //Create table statement Table creation statement

The following is the code of each php file. Friends who need it can directly copy each code and put it in the same directory. You must also create an uplaods folder in the same directory to store uploaded images

PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial 1 2 3 Product Information Management 4 5 6
7 include("menu.php");//Import navigation bar ?> 8

Publish product information

9
10 11121314151617282930313233343536373839404142434445465051
Name:
Type: 18 27
单价:
库存:
图片:
描述:
47    48 49
52
53
54 55 add.php PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial 1 php 2 //执行商品信息的增、删、改的操作 3 4 //一、导入配置文件和函数库文件 5 require("dbconfig.php"); 6 require("function.php"); 7 //二、连接MySQL,选择数据库 8 $link = mysql_connect(HOST,USER,PASS) or die("数据库连接失败"); 9 mysql_select_db(DBNAME,$link); 10 11 12 //三、获取action参数的值,并做对应的操作 13 switch($_GET["action"]) 14 { 15 case "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.验证()省略 24 if(empty($name)) 25 { 26 die("商品名称必须有值"); 27 } 28 //3. Perform image upload 29 $upinfo = uploadFile("pic","./uploads/"); 30 if($upinfo["error"]===false) 31 { 32 die("Picture information upload failed:".$upinfo["info"]); 33 }else 34 { 35 //Upload successful 36 $pic = $upinfo["info"];//Get the name of the successfully uploaded picture 37 38 } 39 //4. Perform image scaling 40 imageUpdateSize('./uploads/'.$pic,50,50); 41 //5. Assemble the sql statement and execute the addition 42 $sql = "insert into goods values(null,'{$name}','{$typeid}', {$price},{$total},'{$pic}','{$note}',{$addtime})"; 43 mysql_query($sql,$link); 44 //6. Judge and output the result 45 if(mysql_insert_id($link)>0) 46 { 47 echo "Product released successfully" ; 48 }else 49 { 50 echo "Product release failed" ; 51 } 52 echo "
View product information"; 53 54 break; 55 case "del": //delete 56 //Get the id number to be deleted and assemble the deletion sql, execute 57 $sql = "delete from goods where id={$_GET['id']}"; 58 59 mysql_query($sql,$link); 60 //Perform image deletion 61 if(mysql_affected_rows($link)>0) 62 { 63 @unlink("./uploads/".$_GET['picname']); 64 @unlink("./uploads/s_".$_GET['picname']); 65 } 66 //Jump to the browsing interface 67 header("Location:index.php"); 68 break; 69 70 case "update": //Modify 71 //1. Get the information to be modified 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. Data verification 80 if(empty($name)) 81 { 82 die("The product name must have a value"); 83 } 84 //3. Determine whether there is an image uploaded 85 if($_FILES['pic']['error']!=4) 86 { 87 //Execute upload 88 $upinfo = uploadFile("pic","./uploads/"); 89 if($upinfo["error"]===false) 90 { 91 die("Picture information upload failed:".$upinfo["info"]); 92 }else 93 { 94 //Upload successful 95 $pic = $upinfo["info"];//Get the name of the successfully uploaded picture 96 //4. Execute scaling when uploading images 97 imageUpdateSize('./uploads/'.$pic,50,50); 98 } 99 } 100 101 102 //5. Execute modifications 103 $sql = "update goods set name='{$name}',typeid={$typeid},price= {$price},total={$total},note='{$note}',pic='{$pic}' where id={$id}"; 104 mysql_query($sql,$link); 105 //6. Determine whether the modification is successful 106 if(mysql_affected_rows($link)>0) 107 { 108 if($_FILES['pic']['error']!=4) 109 { 110 //If there are pictures uploaded, delete the old pictures 111 @unlink("./uploads/".$_POST['oldpic']); 112 @unlink("./uploads/s_".$_POST['oldpic']); 113 } 114 echo "Modification successful" ; 115 }else 116 { 117 echo "Modification failed".mysql_error(); 118 } 119 echo "
View product information"; 120 break; 121 default: 122 echo "Error";break; 123 124 }125 //4. Close the database 126 mysql_close($link); action.php PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial 1 php 2 //Public Information Profile 3 4 //Database information configuration 5 define("HOST","localhost");//Host name 6 define("USER","root"); //Username 7 define("PASS","root"); //Password 8 define("DBNAME","demodb"); //Database name 9 10 //Product type list information 11 $typelist=array(1=>"Clothing",2=>"Digital",3=>"Food" ); 12 13 14 ?> dbconfig.php PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial 1 2 3 Product Information Management 4 5 6
7 include("menu.php");//Import navigation bar ?> 8

Browse product information

9 10

11121314151617181920php 21//Read information from the database and output it to the browser table 22 //1. Import configuration file 23require("dbconfig.php"); 24//2. Connect to the database and select the database 25$link = @mysql_connect(HOST,USER,PASS) or die("Database connection failed"); 26mysql_select_db(DBNAME,$link); 27//3. Execute product information query28$sql="select * from goods"; 29$result = mysql_query($sql,$link); 3031//4. Parse product information (parse result set) 32while($row = mysql_fetch_assoc($result)) 33 { 34echo ""; 35echo ""; 36echo ""; 37echo ""; 38echo ""; 39echo ""; 40echo ""; 41echo ""; 47echo ""; 48 } 49//5.释放结果集,关闭数据库50 ?> 51
Item number Product Name Product pictures Unit price Inventory Add time Operation
{$row["id"]} {$row["name"]} PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial {$row["price"]} {$row["total"]} ".date("Y-m-d H:i:s",$row['addtime'])." 42 $row['pic']}'>删除 43 修改 44 放入购物车 45 46
52
53 54 index.php PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial 1 2 3 商品信息管理 4 5 6
7 php 8 include("menu.php");//导入导航栏 9 //1.导入配置文件 10 require("dbconfig.php"); 11 //2.连接数据库,并选择数据库 12 $link = @mysql_connect(HOST,USER,PASS) or die("数据库连接失败"); 13 mysql_select_db(DBNAME,$link); 14 //3.获取要修改的商品信息 15 $sql="select *from goods where id={$_GET['id']}"; 16 $result = mysql_query($sql,$link); 17 //4.判断是否获取到要编辑的商品信息 18 if($result&&mysql_num_rows($result)>0) 19 { 20 $shop=mysql_fetch_assoc($result);//解析出要修改的商品信息 21 }else 22 { 23 die("没有找到要修改的商品信息"); 24 }25 26 ?> 27

编辑商品信息

28
29 30 31 32 333435363738395152535455565758596061626364656667686970747576777879
名称:
类型: 40 50
单价:
库存:
图片:
描述:
71    72 73
  PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial
80
81
82 83 edit.php PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial 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 13 function uploadFile($filename,$path,$typelist=null) 14 { 15 //1.获取上传文件的名字 16 $upfile = $_FILES[$filename]; 17 if(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);// Store the returned results 22 //2. Filter the error number of uploaded files 23 if($upfile["error"]>0) 24 { 25 switch($upfile["error"]) 26 { 27 case 1: 28 $res["info"]="The uploaded file exceeds the upload_max_filesize option size in php.ini"; 29 break; 30 case 2: 31 $res["info"]="The size of the uploaded file exceeds the MAX_FILE_SIZE option in the HTML form"; 32 break; 33 case 3: 34 $res["info"]="Only part of the file was uploaded"; 35 break; 36 case 4: 37 $res["info"]="No files uploaded"; 38 break; 39 case 6: 40 $res["info"]="Temp folder not found"; 41 break; 42 case 7: 43 $res["info"]="File writing failed"; 44 break; 45 default: 46 $res["info"]="Unknown error!"; 47 break; 48 49 } 50 return $res; 51 } 52 //3. This file size limit 53 if($upfile["size"]>1000000) 54 { 55 $res["info"]="The uploaded file is too large!"; 56 return $res; 57 } 58 //4. Filter type 59 if(!in_array($upfile["type"],$typelist) ) 60 { 61 $res["info"]="Upload type does not match!".$upfile["type"]; 62 return $res; 63 } 64 //5. Initialize the information (generate a random name for the picture) 65 $fileinfo = pathinfo($upfile["name"]); 66 do 67 { 68 $newfile = date("YmdHis").rand(1000,9999).".".$fileinfo["extension"];//Randomly generate names 69 70 }while(file_exists($newfile)); 71 //6. Execute upload processing 72 if(is_uploaded_file($upfile["tmp_name"])) 73 { 74 if(move_uploaded_file($upfile["tmp_name"],$path." /".$newfile)) 75 { 76 //Assign the file name after successful upload to the return array 77 $res["info"]=$newfile; 78 $res["error"]=true; 79 return $res; 80 }else 81 { 82 $res["info"]="Failed to upload file!"; 83 } 84 }else 85 { 86 $res["info"]="Not an uploaded file"; 87 } 88 return $res; 89 } 90 //============================== ===================== 91 /* 92 * 93 * Constant scaling function (implemented in a saved way) 94 * @param string $picname The source of the zoomed processed image 95 * @param int $maxx The maximum width of the scaled image 96 * @param int $maxy The maximum height of the image after scaling 97 * @param string $pre The prefix of the image name after scaling 98 * @param string The returned image name (with path), such as a.jpg=>s_a.jpg 99 */ 100 function imageUpdateSize($picname,$maxx=100,$maxy=100, $pre="s_"){ 101 $info=getimagesize($picname); //Get the picture Basic information 102 $w = $info[0];//Get width 103 $h = $info[1]; // Get height 104 switch($info[2]){ 105 case 1: //gif 106 $im=imagecreatefromgif($picname); 107 break; 108 case 2: //jpg 109 $im=imagecreatefromjpeg($picname); 110 break; 111 case 3: //png 112 $im=imagecreatefrompng($picname); 113 break; 114 default : 115 die("Wrong image type"); 116 } 117 //Calculate scaling ratio 118 if(($maxx/$w)>($maxy/$ h)){ 119 $b=$maxy/$h; 120 }else{ 121 $b=$maxx/$w; 122 }123 //Calculate the scaled size 124 $nw=floor($w*$b); 125 $nh=floor($h*$b); 126 //Create a new image source 127 $nim=imagecreatetruecolor($nw,$nh); 128 //Perform proportional scaling 129 imagecopyresampled($nim,$im,0,0,0,0,$nw,$nh,$w,$h); 130 //Output image 131 $picinfo=pathinfo($picname); 132 $newpicname=$picinfo["dirname"]."/".$pre.$ picinfo["basename"]; 133 134 switch($info[2]){ 135 case 1: 136 imagegif($nim,$newpicname); 137 break; 138 case 2: 139 imagejpeg($nim,$newpicname); 140 break; 141 case 3: 142 imagepng($nim,$newpicname); 143 break; 144 default: 145 echo "Image compression error" ; 146 } 147 //Release image resources 148 imagedestroy($im); 149 imagedestroy($nim); 150 //Return results 151 return $newpicname; 152 } function.php PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial1

Product information management--shopping cart

2
Browse products| 3 Add product| 4 5 My Shopping Cart| 6 Clear shopping cart 7 8 9
menu.php PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial 1 php 2 session_start();//Start session 3 4 ?> 5 6 7 Product Information Management 8 9 10
11 include("menu.php");//Import navigation bar ?> 12

Add items to cart

13 14 php 15 //Read the information to be purchased from the database and add it to the shopping cart 16 //1. Import configuration file 17 require("dbconfig.php"); 18 //2. Connect to the database and select the database 19 $link = @mysql_connect(HOST,USER,PASS) or die("Database connection failed"); 20 mysql_select_db(DBNAME,$link); 21 //3. Perform product information query (obtain the information to be purchased) 22 $sql="select * from goods where id={$_GET['id']}"; 23 $result = mysql_query($sql,$link); 24 25 //4. Determine whether the information you want to purchase is not found, and if so, read and retrieve the information you want to purchase 26 if(empty($result) || mysql_num_rows($result )==0) 27 { 28 die("No information found to buy!"); 29 }else 30 { 31 $shop = mysql_fetch_assoc($result); 32 } 33 $shop["num"]=1;//Add a quantity field 34 //5. Put it in the shopping cart (if the quantity of existing products is accumulated) 35 if(isset($_SESSION["shoplist"]{$shop['id']})) 36 { 37 //If the existing quantity increases by 1 38 $_SESSION["shoplist"][$shop['id']]["num"] ; 39 }else 40 { 41 //If it does not exist, add it to the shopping cart as a newly purchased item 42 $_SESSION["shoplist"][$shop['id']]=$shop; 43 }44 45 ?> 46 47

48 49 addCart PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial 1 php 2 session_start();//Start session 3 4 ?> 5 6 7 Product Information Management 8 9 10
11 include("menu.php");//Import navigation bar ?> 12

View my shopping cart

13

14151617181920212223php 24$sum =0;//Variable defining the total amount25if(isset($_SESSION["shoplist"])){ 26foreach($_SESSION["shoplist"] as$v) 27 { 28echo ""; 29echo ""; 30echo ""; 31echo ""; 32echo ""; 33echo ""; 38echo ""; 39echo ""; 40echo ""; 41$sum =$v["price"]*$v['num']; //Accumulated amount42 } 43 }44 ?> 454647484950
Product ID number Product Name Product pictures Unit price Quantity Subtotal Operation
{$v['id']} {$v['name']} PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial {$v['price']} 34 35 {$v['num']} 36 37 ".($v["price"]*$v['num '])." Delete
Total amount: echo $sum; ?>  
51
52 53 myCart.php PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial 1 php 2 3 //Delete the information in the shopping cart session 4 session_start();//Start session 5 6 //Determine whether to delete an item or clear the shopping cart 7 if($_GET['id']) 8 { 9 //Delete only one product 10 unset($_SESSION['shoplist'][$_GET['id']]); 11 }else 12 { 13 //Clear the products in the session 14 unset($_SESSION["shoplist"]); 15 } 16 17 18 //Jump to the shopping cart interface 19 header("Location:myCart.php"); 20 ?> clearCart.php PHP basic example: product information management system v1.1, information management system v1.1_PHP tutorial 1 php 2 session_start();//Start session 3 //Modify the information in the shopping cart 4 5 //Get the information to be modified 6 7 $id = $_GET['id']; 8 $num = $_GET['num']; 9 10 //Modify product information 11 $_SESSION["shoplist"][$id]["num"] =$num; 12 13 //Prevent the quantity of products from being too small 14 if($_SESSION["shoplist"][$id]["num"]) 15 { 16 $_SESSION["shoplist"][$id]["num"]=1; 17 } 18 //Jump back to my shopping cart interface 19 header("Location:myCart.php"); 20 21 ?> updateCart.php

The following is a screenshot of index.php:

myCart.php screenshot:

Finally, I would like to say: Hahahahahahahahahahahahahahaha! ! ! !

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1005210.htmlTechArticlePHP basic example: commodity information management system v1.1, information management system v1.1 to achieve the goal: use php and Write a product information management system in mysql with a shopping cart function 1. Create data...
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools