The content of this article is about implementing a shopping website in PHP. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it.
This is when I was a graduate student. The teacher asked me to build a shopping website similar to the original Taobao. Because I don’t know PHP, I just learned it for this assignment. It took two weeks to make this website. Here is a summary of this small project.
DONE. User rights management. Including administrators and ordinary users. The administrator has all permissions, including updating website status
Other values for login are username and password. If the username and password are correct, jump to the next page.
ADMIN has permissions to add, delete, update, etc. Users can only view phones, can only add phones to their shopping cart, etc.
DONE. New users: This module is for users without an account. Here the user can create an account to log in. Account creation is done by filling in the registration form with the user’s details such as name, phone, email, etc.
DONE. Product management and display: This module displays mobile phone product information, such as product number, item, name, category, product image, description, functions and product limitations, etc. All of this will be entered into the database so it can be found on the website.
DONE.Search: This module helps customers to ease their search as per their budget or interest. Search can be done on different categories like brand, model name, model number, color or price etc.
DONE: Transaction: In this module, the management of the shopping cart is completed. This module shopper can select any number of items (mobile phones, accessories) and add them to the shopping cart, after purchasing the items from the shopping cart, all the items to be purchased can be viewed again. The shopper can also remove it from the cart if he doesn't like it later. Shoppers can also check the products saved in their cart one by one. As products are checked out of the cart, the total price will be added.
DONE:Shipping: In this module, shoppers can choose the appropriate shipping option. Shoppers have access to a variety of shipping options offered by different service providers.
DONE: Payment: This module describes the payment completed by the customer. Shoppers can choose from different payment methods and provide confidential payment information as required by the selected payment method. Payment information may also include information such as purchase model, quantity and supplier name.
DONE:Reports: In this module, all reports will be generated. Whenever an item is sold or a customer orders a product, an alert should be sent to his supplier immediately via email so that he can ship the item as soon as possible. This module has 3 sub-modules; Stock Report, Order Report and Delivery Report.
Stock reporting will generate a report of available product quantities and product status.
The order report will list the list of products ordered and details of the customer who purchased the product, which was not delivered.
Delivery report will generate a list of products sold and their delivery status.
The following is the code of the above functions and some related explanations:
The simplest main interface:
index.html
//Only one registration and one registration Login link
Phones on saling Phones on saling!
Sign in the website.
Login into the website.
First select the role type: (This function was just practiced at the beginning. In fact, the role selection and registration functions should be placed on one page. , it is now divided into three, namely selection, administrator registration and user registration, which is more troublesome. Later, time was tight, so I didn’t change it anymore. It can actually be merged into one.)
chooseCharacter.html
Sign in to phone website Choose your charactor
Please choose which kind of charactor you want to sign in?
chooseCharacter.php
//After selecting the corresponding role, it will jump to the registration interface of different roles
1) Administrator registration:
adminSign.html
//Administrator registration interface. Administrator registration requires an internal Invitation number (invitation code) before registration can proceed. If you have already registered, you can click the login link below to log in directly and you will be redirected to the login.php interface.
If you have already signed in, please click here to login.Sign in to phone website as admin user Sign in
adminSign.php
//Processing administrator registration request
2) User registration
sign.html
//User registration interface
sign.php
//Process user registration request, collect basic information and add it to the database. If there is missing data, you will not be able to register. A basic test will be done on the password entered twice and the correctness of the email format will be checked.
//After registration, you will jump to the login.php interface, but because after ordinary users register, they will automatically log in for the current user, and store the user's login status in the current cookie, so there is no need to log in again, you can Jump directly from the web link to the mobile purchase interface.
login.php
//User login interface, you can choose administrator user login and ordinary user login.
After logging in as an administrator user, jump to the product management interface. After logging in as an ordinary user, jump to the homepage of the website, which is the mobile purchase interface.
Login in to phone website User Login
Click here to buy phones.
process_login.php//Process login request
"; } if($userName == ""||$pwd == ""){ echo "None of the value can be empty!"; echo "
"; } //declare the sql var and decides the value //$sql; if($selected_Charactor == "admin"){ $sql = "SELECT admin_id FROM admin_info WHERE admin_name = '" . $userName . "' and admin_pwd = '". $pwd ." ' ;" ; $result = executeSql($sql); if ($result[0]) { header('Location: p_manage.php'); } else { echo "Error! Something wrong in your username or password!"; echo "
"; } }else if($selected_Charactor == "user"){ $sql = "SELECT u_id FROM user_info WHERE u_name = '" . $userName ."' and u_pwd = '".$pwd."' ;" ; $result = executeSql($sql); if($result[0]){ setcookie('login_status',true); while ($row = mysqli_fetch_assoc($result[1])){ $u_id=$row["u_id"]; setcookie('u_id',$u_id); } header('Location: showPhones.php'); }else{ echo "Error! Something wrong in your username or password!"; echo "
"; } } ?>
1) Add a new mobile phone:
add_product. html
//Add new mobile phone inventory
add_product.php
//Process add requests
Add new product "; }else{ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "hw"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("Fail to connect!: " . $conn->connect_error); } //执行sql语句 if ($conn->query($sql) === TRUE) { $flag = TRUE; } else { echo "Error: " . $sql . "
" . $conn->error; } $conn->close(); return $flag; } } $p_name=$_POST["name"]; $p_brand=$_POST["brand"]; $p_type=$_POST["type"]; $p_price=$_POST["price"]; $p_inventory=$_POST["inventory"]; $p_descr=$_POST["descr"]; $p_color=$_POST["color"]; $p_image_url=$_POST["url"]; if($p_name ==""||$p_brand ==""||$p_type ==""||$p_price ==""||$p_inventory ==""||$p_descr ==""||$p_color ==""){ echo "You can not provide empty values!"; }else{ $sql = "INSERT INTO product_info(p_name,p_brand,p_type,p_price,p_descr,p_color,p_image_url) VALUES ('".$p_name."','".$p_brand."','".$p_type."','".$p_price."','".$p_descr."','".$p_color."','".$p_image_url."');"; $result = executeSql($sql); if($result){ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "hw"; // 创建连接 $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $select_sql = "SELECT * FROM product_info WHERE p_name = '".$p_name."';"; $result=mysqli_query($conn,$select_sql);//result is a PHP array var_dump($result); $num_rows=mysqli_num_rows($result); //echo $num_rows; mysqli_close($conn); while ($row = mysqli_fetch_assoc($result)){ $p_id=$row["p_id"]; $insert_sql = "INSERT INTO stock_info(p_id,p_inventory) VALUES (".$p_id.",".$p_inventory.");"; $feedback = executeSql($insert_sql); if($feedback){ header("location:p_manage.php"); } } } } ?>
2)管理员管理手机(查看,删除,etc)
p_manage.php
Read product information from database Welcome! Admin user. This is the page of Product Management.
Product ID | Product Name | Product Brand | Product Type | Product Price | Product Inventory | Product Description | Product Color | Product Image | Delete Product | ".$p_id." | "; echo "".$p_name." | "; echo "".$p_brand." | "; echo "".$p_type." | "; echo "".$p_price." | "; echo "".$p_inventory." | "; echo "".$p_descr." | "; echo "".$p_color." | "; //$image = 'https://cdn2.gsmarena.com/vv/pics/apple/apple-iphone-x-new-1.jpg'; $imageData = base64_encode(file_get_contents($p_image_url)); //var_dump($imageData); //echo ''; //echo ''; //echo " | "; ?> | '>Delete | "; $i++; } mysqli_close($conn); ?>
---|
界面如图所示(缩小版的界面)
手机展示界面,并可实现增加产品到购物车,没有实现批量添加,每点击一次手机产品对应的添加按钮,则购物车中增加一条该产品的记录。
添加后会在购物车功能模块处理,如果已经添加够了,也可以直接点击页面最下方的链接,查看购物车。
showPhones.php
//代码和p_manage.php类似,有些功能类似或重合
Product information Welcome! You can buy your own phone here.
Product Name | Product Brand | Product Type | Product Price | Product Inventory | Product Description | Product Color | Product Image | Add to Cart | ".$p_name." | "; echo "".$p_brand." | "; echo "".$p_type." | "; echo "".$p_price." | "; echo "".$p_inventory." | "; echo "".$p_descr." | "; echo "".$p_color." | "; //$image = 'https://cdn2.gsmarena.com/vv/pics/apple/apple-iphone-x-new-1.jpg'; $imageData = base64_encode(file_get_contents($p_image_url)); //var_dump($imageData); echo ''; ?> | &goods_name='>addCart | "; $i++; } mysqli_close($conn); ?>
---|
1)process_shopCart.php//处理添加请求
2)view_shopCart.php//查看购物车
Shop cart View your shop cart here.
Product Name | Product Brand | Product Price | Product Description | Product Color | Counts | Delete from Cart | ".$p_name." | "; echo "".$p_brand." | "; echo "".$p_price."HKD | "; echo "".$p_descr." | "; echo "".$p_color." | "; echo "".$goods_num." | "; ?>'>Delete | "; $singlePrice = $p_price * $goods_num; $totalPrice = $totalPrice + $singlePrice; $totalItem = $totalItem + $goods_num; setcookie("total_item",$totalItem); setcookie("phones_price",$totalPrice); } } //echo $p_info; setcookie('p_info',$p_info); ?>
---|---|---|---|---|---|---|
'>Clear cart |
购物车如下图:
购物车中会展示所有产品的信息,并计算他们的总价格。
3)delCart.php
//如果用户在查看购物车时点击删除某项产品,将该产品从购物车中全部删除
4)clearCart.php
//如果用户在查看购物车时,点击了清空购物车,将当前购物车中内容全部清空
"; echo "
"; $result = session_destroy(); }else{ echo "There is no goods in shop cart!"; }echo "
";echo $result;echo "
";echo "
"; var_dump($_SESSION); header("location:view_shopCart.php");?>
点击购物车中的’shipment’,选择装运物流信息。
shipment.php
Shipment You have already fill the shipment information
Click here to payChoose your shipment way
process_shipment.php
//处理物流信息请求
物流选择界面如图:
1)payInfo.php
//计算商品和物流的总价格并展示,让用户选择支付方式。如果已经选择了支付方式(检查cookie中的值),提升已经选择,并且给出跳转动支付页面的链接。否则让用户选择支付方式,提供了四种,微信,支付宝,信用卡和中国银联,默认选项为支付宝
Shop cart Total money here, please fill your payment information.
Click here to continue
Total Item | Phones Price | Shipment Way | Shipment Price | Total Price | ".$total_item." | "; echo "".$phonesPrice." | "; echo "".$shipment_way." | "; echo "".$shipment_price." | "; echo "".$totalPrice." | "; echo ""; ?>
---|
界面如图:
2)pay_way.php
//将用户支付信息填入数据库表中,并跳转到pay_money.php
3)pay_money.php
//根据payInfo.php中选择的支付方式,打开相应的界面,让用户登录并付钱。
然后将订单信息全部丢给process_order.php处理
//这里有一点需要特别说明的是,因为这是一个练习,数据都是虚拟的,所以无法从支付宝或者微信,银联等获知用户支付已经支付成功,所以这里将是否已经支付的判定设置为,只要用户填写了付款信息,并点击付款,打开了支付页面,这里就在cookie中设置为已支付状态
window.open('https://auth.alipay.com/login/index.htm?goto=https%3A%2F%2Fmy.alipay.com%2Fportal%2Fi.htm')"; //$image_url = "https://www.hkelectric.com/zh/CustomerServices/PublishingImages/Alipay_Download_QR.jpg"; //$imageData = base64_encode(file_get_contents($image_url)); //echo ''; }else if($payWay == "WeChatPay"){ //$image_url = "https://3.bp.blogspot.com/-ymZs4Aij_f8/WnXUq9v5Z9I/AAAAAAAAFeA/Zrnru65sDLEgGbVbJ_KevD9_izoL3YO5wCLcBGAs/s1600/wechat.jpg"; //$imageData = base64_encode(file_get_contents($image_url)); //var_dump($imageData); //echo ''; echo ""; }else if($payWay == "Credit"){ echo ""; }else if($payWay == "UnionPay"){ echo ""; } setcookie('pay_status',true);$sql = "UPDATE payment_info SET pay_status=1 WHERE pay_id = ".$_COOKIE['pay_id'].";";$result = executeSql($sql);if($result[0]){ echo "
"; echo "
"; echo "Click here to see order information."; }else{ echo "You have to pay first!"; } ?>
1)process_order.php
//将订单的信息填入到数据库表中
2)view_order.php
//查看订单信息,并给出生成报告的链接
Order Information
Order id | User | Tracking Number | Product Price | Delivery Price | Total Items | Total Price | Payment ID | Pay Status | ".$o_id." | "; echo "".$u_id." | "; echo "".$tracking_num." | "; echo "".$phones_price."HKD | "; echo "".$shipment_price."HKD | "; echo "".$total_item." | "; echo "".$total_price."HKD | "; echo "".$pay_id." | "; if($pay_status){ echo "Paid | "; }else{ echo "Not Paid | "; } echo ""; echo "
---|
1)eOrderReport.php
//导出订单报告
2)eStockReport.php
//导出库存报告
Export Report Host = "ssl://smtp.gmail.com"; $mail = new PHPMailer(); //实例化 $mail->IsSMTP(); // 启用SMTP //$mail->Host = "smtp.163.com"; //SMTP服务器 163邮箱例子 $mail->Host = "smtp.126.com"; //SMTP服务器 126邮箱例子 //$mail->Host = "smtp.qq.com"; //SMTP服务器 qq邮箱例子 $mail->Port = 25; //邮件发送端口 $mail->SMTPAuth = true; //启用SMTP认证 $mail->CharSet = "UTF-8"; //字符集 $mail->Encoding = "base64"; //编码方式 $mail->Username = "ninnyyan@126.com"; //你的邮箱 $mail->Password = "sandy.126"; //你的密码 $mail->Subject = "Product information updating"; //邮件标题 $mail->From = "ninnyyan@126.com"; //发件人地址(也就是你的邮箱) $mail->FromName = "ninny"; //发件人姓名 $address = "714921503@qq.com";//收件人email $mail->AddAddress($address, "feng"); //添加收件人1(地址,昵称) //$mail->AddAttachment('xx.xls','我的附件.xls'); // 添加附件,并指定名称 $mail->IsHTML(true); //支持html格式内容 //$mail->AddEmbeddedImage("logo.jpg", "my-attach", "logo.jpg"); //设置邮件中的图片 $mail->Body = $file_stream; //邮件主体内容 //发送if(!$mail->Send()){ echo "Fialed to send " . $mail->ErrorInfo; } else { echo "Successfully send the email!"; } } php_sendmail($file_stream); header('location:view_order.php');?>
3)eDeliveryReport.php
//导出物流报告
做了一个分类搜索的功能,用的就是数据库的模糊查询,很简单
1)search.html
//页面
2)search.php
//处理查询请求
"; } if($selected_Condition == "brand"){ $value = $_POST["value"]; if($value ==""){ echo "The value can't be empty!"; echo "
"; }else{ $sql = "SELECT * FROM product_info WHERE p_brand LIKE '%".$value."%';"; showResult($sql); } }else if($selected_Condition == "name"){ $value = $_POST["value"]; if($value ==""){ echo "The value can't be empty!"; echo "
"; }else{ $sql = "SELECT * FROM product_info WHERE p_name LIKE '%".$value."%';"; showResult($sql); } }else if($selected_Condition == "type"){ $value = $_POST["value"]; if($value ==""){ echo "The value can't be empty!"; echo "
"; }else{ $sql = "SELECT * FROM product_info WHERE p_type LIKE '%".$value."%';"; showResult($sql); } }else if($selected_Condition == "color"){ $value = $_POST["value"]; if($value ==""){ echo "The value can't be empty!"; echo "
"; }else{ $sql = "SELECT * FROM product_info WHERE p_color LIKE '%".$value."%';"; showResult($sql); } }else if($selected_Condition == "price"){ $low_range = $_POST["low_range"]; $high_range = $_POST["high_range"]; if($low_range ==""||$high_range == ""){ echo "The range can't be empty!"; echo "
"; }else{ $sql = "SELECT * FROM product_info WHERE p_price BETWEEN ".$low_range." AND ".$high_range.";"; showResult($sql); } } function showResult($sql){ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "hw"; $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result=mysqli_query($conn,$sql);//result is a PHP array $num_rows=mysqli_num_rows($result); mysqli_close($conn); if($num_rows == 0){ echo "There is no meeted results."; }else{ echo '
Product Name | "; echo "Product Brand | "; echo "Product Type | "; echo "Product Price | "; echo "Product Description | "; echo "Product Color | "; echo "Product Image | "; echo "
---|---|---|---|---|---|---|
".$p_name." | "; echo "".$p_brand." | "; echo "".$p_type." | "; echo "".$p_price." | "; echo "".$p_descr." | "; echo "".$p_color." | "; $imageData = base64_encode(file_get_contents($p_image_url)); echo ''; echo " |
1)购物车用session实现
2)其他各种用户登录状态,产品id等信息,均存储在cookie数组中
3)当某种产品卖出后,会从数据库中将该产品的库存减去订单中相应的数量。
下面是对数据库设计的一个说明,交作业用的。
Design ideas of relational schema: Since the website will not be too complex, so I just design basic fields of the whole website logic. As for the tables “order_info” and “orderDetailRecord_info”, I separate order information into two tables to solve the problem that one order may have two types of products. Plus, the “p_image_url” field in the table “product_info”, will be used for analyzing url of images of products. Plus plus: actually an order may conclude many products, every products may choose different delivery method, but here we simplify it and assume that an order only have one delivery method.
另外需要说明的是,
delivery_info表和payment_info表中分别加入了一个random字段,是因为在写php处理的过程中,产生了相应的需要,具体处理请看代码。
The following are the specific table names and fields:
Some codes could have been written more concisely and merged together.
Connecting to the database and other operations of executing SQL statements can be encapsulated and called in separate files. It is also relatively simple to process them wherever they are used.
There are two ways of linking the database, which are not unified.
PHP implements WeChat web page login authorization development
The above is the detailed content of PHP implements shopping website. For more information, please follow other related articles on the PHP Chinese website!