时间:2021-07-01 10:21:17 帮助过:45人阅读
这篇文章介绍的内容是关于PHP实现购物网站 ,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
这是我在研究生期间,老师要求做的一个类似原始淘宝网的购物网站,因为不会PHP,为了写这个作业而新学的。做这个网站用了两周时间,在此把这个小项目做一个总结。
DONE. 用户权限管理。包括管理员和普通用户。管理员有所有权限,包括更新网站状态
登录的其他值为用户名和密码,用户名和密码正确,跳转到下一页。
ADMIN具有添加,删除,更新等权限。用户只能查看手机,只能添加到购物车中的手机等。
DONE.新用户:此模块适用于没有帐户的用户。这里用户可以创建一个帐户来登录。账户的创建是通过填写注册表单和用户的详细信息,如姓名,电话,电子邮件等来完成的。
DONE.产品管理和展示:该模块展示手机产品信息,如产品编号,项目,名称,类别,产品图像,说明,功能和产品限制等。所有这些都将输入到数据库,因此可以在网站上找到。
DONE.搜索:该模块可帮助客户根据自己的预算或兴趣来放松搜索。搜索可以在不同的类别上完成,如品牌,型号名称,型号,颜色或价格等。
DONE:交易:在此模块中,购物车的管理已完成。此模块购物者可以选择任意数量的物品(手机,配件)并将它们添加到购物车,在从购物车购买物品后,所有要购买的物品都可以再次查看。如果他以后不喜欢,购物者也可以从购物车中取出。购物者还可以逐一检查购物车中保存的产品。由于产品从购物车中检出,总价格将相加。
DONE:装运:在这个模块中,购物者可以选择合适的装运选项。购物者可以使用不同服务提供商提供的各种运送选项。
DONE:付款:该模块描述了客户完成的付款。购物者可以选择不同的支付方式,并根据所选的支付方式的要求提供机密的支付信息。付款信息还可能包括购买型号,数量和供应商名称等信息。
DONE:报告:在此模块中,将生成所有报告。无论何时出售物品或客户订购产品,都应立即通过电子邮件向其供应商发送警报,以便他可以尽快装运该物品。该模块有3个子模块;股票报告,订单报告和交付报告。
股票报告将生成可用产品数量和产品状态的报告。
订单报告将列出订购的产品清单以及购买该产品的客户详细信息,这些信息未送达。
交付报告将生成已售出产品清单及其交付状态。
下面是以上功能的代码以及一些相关的解释:
最简单的主界面:
index.html
//只放了一个注册一个登录的链接
<html><head><meta charset="utf-8"><title>Phones on saling</title></head> <h1>Phones on saling!</h1>
<a href="chooseCharactor.html" target="_blank">Sign in the website.</a><br><br>
<a href="login.php" target="_blank">Login into the website.</a></html>首先要选择角色类型:(这个功能是刚开始练习做的,其实应该把角色选择和注册功能都放在一个页面里,现在分为了三个,分别是选择,管理员注册和用户注册,比较麻烦。后来时间紧,就没有再改了,实际可以合并为一个。)
chooseCharacter.html
<html><head>
<meta charset="utf-8">
<title>Sign in to phone website</title></head>
<h1>Choose your charactor</h1>
Please choose which kind of charactor you want to sign in? <form action="chooseCharactor.php" method="get">
<select name="q">
<option value="">Choose charactor</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select><br>
<input type="submit" value="Submit">
</form></html>chooseCharacter.php
//选择相应的角色后,会跳转到不同角色的注册界面
<!DOCTYPE html><html><head>
<title>Choose charactor</title></head><body>
<?php $q = isset($_GET['q'])? htmlspecialchars($_GET['q']) : '';
if($q == "") {
echo "You must choose a charactor!";
}else if($q != ""){
if($q =='admin') {
header('Location: adminSign.html');
} else if($q =='user') {
header('Location: sign.html');
}
}
?></body></html>1)管理员注册:
adminSign.html
//管理员注册的界面。管理员注册需要拿到内部的Invitation number(邀请码),注册方可进行。如果已经注册,可以点击下方的login链接,直接登录,将跳转到login.php界面。
<html><head>
<meta charset="utf-8">
<title>Sign in to phone website as admin user</title></head>
<h1>Sign in</h1>
<form action="adminSign.php" method="post">
User name:<input type="text" name="username"><br>
User password:<input type="password" name="psw"><br>
Confirm user password:<input type="password" name="cofpsw"><br>
Invitation number:<input type="text" name="invtnum"><br>
<input type="submit" name="submit">
</form>
If you have already signed in, please click here to login.<br>
<a href="login.html" target="_blank">Login into the website.</a></html>adminSign.php
//处理管理员注册请求
<!DOCTYPE html><html><head>
<title>Sign in the phone web as admin user, success!</title></head><body>
<?php
include 'executeSql.php'; $userName = $_POST["username"]; $pwd = $_POST["psw"]; $cofPsw = $_POST["cofpsw"]; $invtNum = $_POST["invtnum"];
if($userName == ""||$pwd == ""||$cofPsw == ""|| $invtNum == ""){
echo "None of the value can be empty!";
}else if($pwd != $cofPsw){
echo "The password entered for two time is not same!";
}else if($invtNum != "SN90IE58KP"){
echo "The invitation number is wrong!";
}else{
echo "All values are right, your have sucessfully sign in as admin user!"; $sql = "INSERT INTO admin_info (admin_name,admin_pwd) VALUES('" . $userName . "','" . $pwd . "');";
//$sql = "INSERT INTO admin_info (admin_name,admin_pwd) VALUES('superadmin','admin123');";
//echo $sql;
executeSql($sql);
}
?></body></html>2)用户注册
sign.html
//用户注册界面
<html><head><meta charset="utf-8"><title>Sign in to phone website</title></head> <h1>Sign in</h1><form action="sign.php" method="post">
User name:<input type="text" name="username"><br>
User password:<input type="password" name="psw"><br>
Confirm user password:<input type="password" name="cofpsw"><br>
Phone:<input type="text" name="phone"><br>
Email:<input type="email" name="email"><br>
<input type="submit" name="submit"></form></html>sign.php
//处理用户注册请求,收集基本信息并加入到数据库。如果存在数据缺失,则不能注册,对两次输入的密码做了基本的检测,并检测邮箱格式的正确性。
//注册后会跳转到login.php界面,但是因为普通用户注册后,会自动为当前用户登录,并在当前的cookie中存储用户登录的状态,因此不需要再登录一次,可以直接由网页链接跳转到手机购买界面。
<!DOCTYPE html><html><head>
<meta charset="utf-8">
<title>Sign in sucess!</title>
<style>
.button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; }
.table{ border-style:solid; border-color:#98bf21; align-self: center; align-items: center; }
/*.pcss5-right{width:320px; height:120px;border:1px solid #F00;float:right} */
.pcss5-right{float:right;}
/* css注释:对pcss5-right设置float:right即可让对象靠右浮动 */
</style></head><body>
<?php
function executeSql($sql){ $flag = false; $feedback = array();
if($sql == ""){
echo "Error! Sql content is empty!";
}else{ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "hw"; $conn = mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} $query_result=mysqli_query($conn,$sql);//query_result is a PHP array
if($query_result){ $flag = true; $feedback = $query_result;
//$num_rows=mysqli_num_rows($query_result);
}
return array($flag,$feedback);
}
} $userName = $_POST["username"]; $pwd = $_POST["psw"]; $cofPsw = $_POST["cofpsw"]; $phone = $_POST["phone"]; $email = $_POST["email"];
if($userName == "" || $pwd == "" || $cofPsw == "" || $phone == "" || $email == ""){
echo "None of the value can be empty!";
}
else if($pwd != $cofPsw){
echo "The password entered for two time is not same!";
}else if ($pwd == $cofPsw){ $sql = "INSERT INTO user_info (u_name,u_pwd,u_phone,u_email) VALUES('" .$userName ."','" . $pwd ."','" . $phone . "','" . $email . "');"; $result = executeSql($sql);
if($result){ $select_sql = "SELECT u_id FROM user_info WHERE u_name = '".$userName."';"; $result = executeSql($select_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:login.php");
}
}
}
?></body></html>login.php
//用户登录的界面,可以选择管理员用户登录和普通用户登录。
作为管理员用户登录后,跳转到产品管理界面。作为普通用户登录后,跳转到网站主页,即手机购买界面。
<html><head><meta charset="utf-8"><title>Login in to phone website</title><style>
.button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; align-self:right; float: left; }
.body{font-family:Arial,Helvetica,sans-serif;font-size:20px;}
</style><h2>User Login</h2></head>
<body class = "body">
<?php
if(isset($_COOKIE['login_status'])){
echo "Login already.";
?>
<br>
<br>
<a href='showPhones.php'>Click here to buy phones.</a>
<?php
}else{
?>
<form action="process_login.php" method="post">
<select name="character">
<option value="">Choose your character</option>
<option value="admin">admin</option>
<option value="user">user</option>
</select><br>
User name:<input type="text" name="username"><br>
User password:<input type="password" name="psw"><br>
<input type="submit" class = "button" name="submit" value="Choose">
</form>
<?php
}
?>
</body></html>process_login.php//处理登录请求
<!DOCTYPE html><html><body>
<?php
function executeSql($sql){ $flag = false; $feedback = array();
if($sql == ""){
echo "Error! Sql content is empty!";
}else{ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "hw"; $conn = mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} $query_result=mysqli_query($conn,$sql);//query_result is a PHP array
if($query_result){ $flag = true; $feedback = $query_result;
//$num_rows=mysqli_num_rows($query_result);
}
return array($flag,$feedback);
}
} $userName = $_POST["username"]; $pwd = $_POST["psw"];
if(isset($_POST["submit"])){ $selected_Charactor = $_POST["character"];
}else{
echo "You have choose the wrong charactor!";
echo "<br>";
}
if($userName == ""||$pwd == ""){
echo "None of the value can be empty!";
echo "<br>";
}
//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 "<br>";
}
}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 "<br>";
}
}
?></body></html>1)增加新的手机:
add_product.html
//增加新的手机库存
<html><head>
<title>Add new product</title>
<style>
.button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; align-self:right; float: right; }
.table{ border-style:solid; border-color:#98bf21; align-self: center; align-items: center; width: "12%"; height: "20%"; }
</style></head><h1 align="center">Hello admin user, you can add a new product into database!</h1><body>
<form action="add_product.php" method="post">
<table align="center" class = "table" border="1">
<th>Product Name</th>
<th>Product Brand</th>
<th>Product Type</th>
<th>Product Price</th>
<th>Product Inventory</th>
<th>Product Description</th>
<th>Product Color</th>
<th>Product Url</th>
<tr>
<td><input type="text" name="name"></td>
<td><input type="text" name="brand"></td>
<td><input type="text" name="type"></td>
<td><input type="text" name="price"></td>
<td><input type="text" name="inventory"></td>
<td><input type="text" name="descr"></td>
<td><input type="text" name="color"></td>
<td><input type="text" name="url"></td>
</tr>
</table>
<input type="submit" class = "button" name="submit" value="Submit">
</form></body></html>add_product.php
//处理增加请求
<!DOCTYPE html><html><head>
<title>Add new product</title></head><body>
<?php
function executeSql($sql){ $flag = false;
if($sql == ""){
echo "Error! Sql content is empty!";
echo "<br>";
}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 . "<br>" . $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");
}
}
}
}
?><br></body></html>2)管理员管理手机(查看,删除,etc)
p_manage.php
<!DOCTYPE html><html><head>
<meta charset="utf-8">
<title>Read product information from database</title>
<style>
.button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; align-self:right; float: right; }
.table{ border-style:solid; border-color:#98bf21; align-self: center; align-items: center; width: "10%"; }
a:link {color:#000000;} /* 未访问链接*/
a:visited {color:#4CAF50;} /* 已访问链接 */
a:hover {color:#4CAF50;} /* 鼠标移动到链接上 */
a:active {color:#0000FF;} /* 鼠标点击时 */
</style></head>
<h1 align="center">Welcome! Admin user. This is the page of Product Management.</h1>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script>
function newPage(){
window.location.assign("add_product.html")
} function deleteProduct(p_id){
$.ajax({
type: "POST",
url: "deleteProduct.php",
data: "pid="+p_id,
success: function(msg){
window.location.reload();
}
});
} </script><body>
<table border="1" align="center" class = "table">
<tr>
<th align="center" width="10%">Product ID</th>
<th align="center" width="10%">Product Name</th>
<th align="center" width="10%">Product Brand</th>
<th align="center" width="10%">Product Type</th>
<th align="center" width="10%">Product Price</th>
<th align="center" width="10%">Product Inventory</th>
<th align="center" width="10%">Product Description</th>
<th align="center" width="10%">Product Color</th>
<th align="center" width="10%">Product Image</th>
<th align="center" width="10%">Delete Product</th>
</tr>
<?php $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();
} $sql = "SELECT * FROM product_info;"; $result=mysqli_query($conn,$sql);//result is a PHP array $num_rows=mysqli_num_rows($result);
//echo $num_rows; $i=0;
while ($row = mysqli_fetch_assoc($result)){ $p_id=$row["p_id"]; $p_name=$row["p_name"]; $p_brand=$row["p_brand"]; $p_type=$row["p_type"]; $p_price=$row["p_price"]; $p_inventory=0; $select_sql = "SELECT p_inventory FROM stock_info WHERE p_id = ".$p_id.";"; $select_result=mysqli_query($conn,$select_sql); $select_num_rows=mysqli_num_rows($result);
if($select_num_rows){
while($select_rows = mysqli_fetch_assoc($select_result)){ $p_inventory=$select_rows["p_inventory"];
}
}else{
echo "not fetch";
} $p_descr=$row["p_descr"]; $p_color=$row["p_color"]; $p_image_url = $row["p_image_url"];
echo "<tr>";
echo "<td align='center'>".$p_id."</td>";
echo "<td align='center'>".$p_name."</td>";
echo "<td align='center'>".$p_brand."</td>";
echo "<td align='center'>".$p_type."</td>";
echo "<td align='center'>".$p_price."</td>";
echo "<td align='center'>".$p_inventory."</td>";
echo "<td align='center'>".$p_descr."</td>";
echo "<td align='center'>".$p_color."</td>";
//$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 '<p class="img">';
echo '<td align="center"><img src="data:image/jpeg;base64,'.$imageData.'" alt="Forest" width="120" height="120"></td>';
//echo '</p>';
//echo "<td><input type='button' value='Delete' onclick='deleteProduct(".$p_id.")'></td>";
?>
<td align="center"><a href='deleteProduct.php?goods_id=<?php echo $p_id; ?>'>Delete</a></td>
<?php
echo "</tr>"; $i++;
}
mysqli_close($conn);
?>
</table>
<br><br>
<p class="pcss5-right">
<input type="button" class = "button" value="Add new product" onclick="newPage()">
</p></body></html>界面如图所示(缩小版的界面) 
手机展示界面,并可实现增加产品到购物车,没有实现批量添加,每点击一次手机产品对应的添加按钮,则购物车中增加一条该产品的记录。
添加后会在购物车功能模块处理,如果已经添加够了,也可以直接点击页面最下方的链接,查看购物车。
showPhones.php
//代码和p_manage.php类似,有些功能类似或重合
<!DOCTYPE html><html><head>
<meta charset="utf-8">
<title>Product information</title>
<style>
.button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; align-self:right; float: right; }
.table{ border-style:solid; border-color:#98bf21; align-self: center; align-items: center; width: "10%"; }
.body{font-family:Arial,Helvetica,sans-serif;font-size:20px;}
a:link {color:#000000;} /* 未访问链接*/
a:visited {color:#4CAF50;} /* 已访问链接 */
a:hover {color:#4CAF50;} /* 鼠标移动到链接上 */
a:active {color:#0000FF;} /* 鼠标点击时 */
</style></head>
<h2 align='center'>Welcome! You can buy your own phone here.</h2><body class="body">
<table border="1" class="table" align='center'>
<tr>
<th align='center' width="10%">Product Name</th>
<th align='center' width="10%">Product Brand</th>
<th align='center' width="10%">Product Type</th>
<th align='center' width="10%">Product Price</th>
<th align='center' width="10%">Product Inventory</th>
<th align='center' width="10%">Product Description</th>
<th align='center' width="10%">Product Color</th>
<th align='center' width="10%">Product Image</th>
<th align='center' width="10%">Add to Cart</th>
</tr>
<?php $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();
} $sql = "SELECT * FROM product_info;"; $result=mysqli_query($conn,$sql);//result is a PHP array $num_rows=mysqli_num_rows($result);
//echo $num_rows; $i=0;
while ($row = mysqli_fetch_assoc($result)){ $p_id=$row["p_id"]; $p_name=$row["p_name"]; $p_brand=$row["p_brand"]; $p_type=$row["p_type"]; $p_price=$row["p_price"]; $p_inventory=0; $select_sql = "SELECT p_inventory FROM stock_info WHERE p_id = ".$p_id.";"; $select_result=mysqli_query($conn,$select_sql); $select_num_rows=mysqli_num_rows($result);
if($select_num_rows){
while($select_rows = mysqli_fetch_assoc($select_result)){ $p_inventory=$select_rows["p_inventory"];
}
}else{
echo "not fetch";
} $p_descr=$row["p_descr"]; $p_color=$row["p_color"]; $p_image_url = $row["p_image_url"];
echo "<tr>";
echo "<td align='center'>".$p_name."</td>";
echo "<td align='center'>".$p_brand."</td>";
echo "<td align='center'>".$p_type."</td>";
echo "<td align='center'>".$p_price."</td>";
echo "<td align='center'>".$p_inventory."</td>";
echo "<td align='center'>".$p_descr."</td>";
echo "<td align='center'>".$p_color."</td>";
//$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 '<td align="center"><img src="data:image/jpeg;base64,'.$imageData.'"></td>';
?>
<td><a align='center' href='process_shopCart.php?goods_id=<?php echo $p_id; ?>&goods_name=<?php echo $p_name; ?>'>addCart</a></td><?php
echo "</tr>"; $i++;
}
mysqli_close($conn);
?>
</table>
<br><br>
<a align='right' href='view_shopCart.php'>Enough adding, click here to shopcart.</a>
<br><br><br></body></html>1)process_shopCart.php//处理添加请求
<!DOCTYPE html>
<html>
<head>
<title>All fees of shipment.</title>
</head>
<body> <?php
function executeSql($sql){
$flag = false; $feedback = array(); if($sql == ""){ echo "Error! Sql content is empty!";
}else{ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "hw"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error();
} $query_result=mysqli_query($conn,$sql);//query_result is a PHP array
if($query_result){ $flag = true; $feedback = $query_result; //$num_rows=mysqli_num_rows($query_result);
} return array($flag,$feedback);
}
} $unitPrice = 0.0; if(isset($_POST["submit"])){ $orignLocation = $_POST["orgn_location"]; $targetLocation = $_POST["trgt_location"]; $company = $_POST["company"]; if($company == "shun_feng"){$unitPrice = 80.0;setcookie("shipment_way",$company);} if($company == "zhong_tong"){$unitPrice = 40.0;setcookie("shipment_way",$company);} if($company == "yuan_tong"){$unitPrice = 50.0;setcookie("shipment_way",$company);} if($company == "yun_da"){$unitPrice = 39.8;setcookie("shipment_way",$company);} if($company == "shen_tong"){$unitPrice = 57.6;setcookie("shipment_way",$company);} $totalItem = $_COOKIE['total_item']; $shipmentPrice = $unitPrice * $totalItem; $numbers = range (1,1000000);
//shuffle 将数组顺序随即打乱
shuffle ($numbers);
//array_slice 取该数组中的某一段
$num=1;
$result = array_slice($numbers,0,$num);
$d_random = $result[0]; $sql = "INSERT INTO delivery_info (d_company, d_init_add, d_trgt_add, d_price, d_random)
VALUES ('".$company."', '".$orignLocation."', '".$targetLocation."',".$shipmentPrice.",".$d_random.");"; $result = executeSql($sql); if($result[0]){
setcookie('shipment_price',$shipmentPrice); $select_sql = "SELECT d_id FROM delivery_info WHERE d_random = ".$d_random.";"; $select_result = executeSql($select_sql); if($select_result[0]){ while ($row = mysqli_fetch_assoc($select_result[1])){ //var_dump($row);
$d_id=$row["d_id"];
setcookie('d_id',$d_id);
setcookie('shipment_status',true);
}
}
}
}
header("location:payInfo.php"); ?></body>
</html>2)view_shopCart.php//查看购物车
<?php
session_start();
?><html><head>
<meta charset="utf-8">
<title>Shop cart</title></head><h1>View your shop cart here.</h1><body>
<table border="1">
<tr>
<th>Product Name</th>
<th>Product Brand</th>
<th>Product Price</th>
<th>Product Description</th>
<th>Product Color</th>
<th>Counts</th>
<th>Delete from Cart</th>
</tr>
<?php $totalPrice = 0; $totalItem = 0; $p_info = 0;
if(isset($_SESSION['shop-cart'])){
foreach ($_SESSION['shop-cart'] as $item){ $p_id = $item[0]; $p_name = $item[1]; $goods_num = $item[2]; $p_info = $p_info.$p_id.",".$goods_num."/"; $servername = "localhost"; $username = "root"; $password = ""; $dbname = "hw"; $conn = mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} $sql = "SELECT * FROM product_info WHERE p_id =".$p_id.";"; $result=mysqli_query($conn,$sql);//result is a PHP array $num_rows=mysqli_num_rows($result);
//echo $num_rows;
mysqli_close($conn);
while ($row = mysqli_fetch_assoc($result)){ $p_brand=$row["p_brand"]; $p_type=$row["p_type"]; $p_price=$row["p_price"];
//$p_inventory=$row["p_inventory"]; $p_descr=$row["p_descr"]; $p_color=$row["p_color"];
echo "<tr>";
echo "<td>".$p_name."</td>";
echo "<td>".$p_brand."</td>";
echo "<td>".$p_price."HKD</td>";
echo "<td>".$p_descr."</td>";
echo "<td>".$p_color."</td>";
echo "<td>".$goods_num."</td>";
?>
<td><a href='delCart.php?goods_id=<?php echo $p_id; ?>'>Delete</a></td>
<?php
echo "</tr>"; $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);
?>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href='clearCart.php?goods_id=<?php echo $p_id; ?>'>Clear cart</a></td>
<td>
<?php
echo "".$totalItem." Items. ";
echo "Totol prize: ".$totalPrice." HKD";
?>
</td>
</tr>
</table>
<br>
<a href='shipment.php'>Shipment</a>
<br>
<?php
}else{
echo "The shop cart is empty!";
?>
<br><br>
<a href='showPhones.php'>Back to add goods</a>
<?php
}
?></body></html>购物车如下图: 
购物车中会展示所有产品的信息,并计算他们的总价格。
3)delCart.php
//如果用户在查看购物车时点击删除某项产品,将该产品从购物车中全部删除
<?phpsession_start();//$p_name = $_GET["goods_name"];$p_id = $_GET["goods_id"];$goods_num = 1;function id_inarray($findID, $cart_array){
$flag = false; $counter = 0; foreach ($cart_array as $itemList) { if (strcmp($itemList[0], $findID) == 0) { $flag = true; break;
} $counter++;
} return array($flag, $counter);
}$result = id_inarray($p_id,$_SESSION['shop-cart']);if($result[0]){ //如果存在该项,从session中删除
if(isset($result[1])){ unset($_SESSION['shop-cart'][$result[1]]); $_SESSION['shop-cart'] = array_values($_SESSION['shop-cart']);
}
}else{ echo "Cannot delete non-existent items!";
}
header("location:view_shopCart.php");?>4)clearCart.php
//如果用户在查看购物车时,点击了清空购物车,将当前购物车中内容全部清空
<?phpsession_start();$p_id = $_GET["goods_id"];echo $p_id;if(isset($_SESSION['shop-cart'])){ echo "destroy session"; echo "<br>"; echo "<br>"; $result = session_destroy();
}else{ echo "There is no goods in shop cart!";
}echo "<br>";echo $result;echo "<br>";echo "<br>";
var_dump($_SESSION);
header("location:view_shopCart.php");?>点击购物车中的’shipment’,选择装运物流信息。
shipment.php
<html><head>
<meta charset="utf-8">
<title>Shipment</title></head><?php
if(isset($_COOKIE['shipment_status'])){
?><h1>You have already fill the shipment information</h1><body><a href='payInfo.php'>Click here to pay</a></body><?php
}
else{
?><h1>Choose your shipment way</h1><body>
<form action="process_shipment.php" method="post">
<table>
<th>Delivery Company</th>
<th>Orign Location</th>
<th>Target Location</th>
<tr>
<td>
<select name="company">
<option value="">Choose Company</option>
<option value="shun_feng">Shun Feng</option>
<option value="zhong_tong">Zhong Tong</option>
<option value="yuan_tong">Yuan Tong</option>
<option value="yun_da">Yun Da</option>
<option value="shen_tong">Shen Tong</option>
</select><br>
</td>
<td><input type="text" name="orgn_location"></td>
<td><input type="text" name="trgt_location"></td>
</tr>
</table>
<input type="submit" name="submit" value="Submit">
</form></body><?php
}
?></html>process_shipment.php
//处理物流信息请求
<!DOCTYPE html><html><head>
<title>All fees of shipment.</title></head><body>
<?php
function executeSql($sql){ $flag = false; $feedback = array();
if($sql == ""){
echo "Error! Sql content is empty!";
}else{ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "hw"; $conn = mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} $query_result=mysqli_query($conn,$sql);//query_result is a PHP array
if($query_result){ $flag = true; $feedback = $query_result;
//$num_rows=mysqli_num_rows($query_result);
}
return array($flag,$feedback);
}
} $unitPrice = 0.0;
if(isset($_POST["submit"])){ $orignLocation = $_POST["orgn_location"]; $targetLocation = $_POST["trgt_location"]; $company = $_POST["company"];
if($company == "shun_feng"){$unitPrice = 80.0;setcookie("shipment_way",$company);}
if($company == "zhong_tong"){$unitPrice = 40.0;setcookie("shipment_way",$company);}
if($company == "yuan_tong"){$unitPrice = 50.0;setcookie("shipment_way",$company);}
if($company == "yun_da"){$unitPrice = 39.8;setcookie("shipment_way",$company);}
if($company == "shen_tong"){$unitPrice = 57.6;setcookie("shipment_way",$company);} $totalItem = $_COOKIE['total_item']; $shipmentPrice = $unitPrice * $totalItem; $numbers = range (1,1000000);
//shuffle 将数组顺序随即打乱
shuffle ($numbers);
//array_slice 取该数组中的某一段
$num=1;
$result = array_slice($numbers,0,$num);
$d_random = $result[0]; $sql = "INSERT INTO delivery_info (d_company, d_init_add, d_trgt_add, d_price, d_random)
VALUES ('".$company."', '".$orignLocation."', '".$targetLocation."',".$shipmentPrice.",".$d_random.");"; $result = executeSql($sql);
if($result[0]){
setcookie('shipment_price',$shipmentPrice); $select_sql = "SELECT d_id FROM delivery_info WHERE d_random = ".$d_random.";"; $select_result = executeSql($select_sql);
if($select_result[0]){
while ($row = mysqli_fetch_assoc($select_result[1])){
//var_dump($row); $d_id=$row["d_id"];
setcookie('d_id',$d_id);
setcookie('shipment_status',true);
}
}
}
}
header("location:payInfo.php");
?></body></html>物流选择界面如图: 
1)payInfo.php
//计算商品和物流的总价格并展示,让用户选择支付方式。如果已经选择了支付方式(检查cookie中的值),提升已经选择,并且给出跳转动支付页面的链接。否则让用户选择支付方式,提供了四种,微信,支付宝,信用卡和中国银联,默认选项为支付宝
<html><head>
<meta charset="utf-8">
<title>Shop cart</title></head><h1>Total money here, please fill your payment information.</h1><body>
<?php
if(isset($_COOKIE['pay_way'])){
echo "You have fill the payment information.";
?>
<br>
<a href='pay_money.php'>Click here to continue</a>
<?php
}
else{
?>
<table border="1">
<tr>
<th>Total Item</th>
<th>Phones Price</th>
<th>Shipment Way</th>
<th>Shipment Price</th>
<th>Total Price</th>
</tr>
<?php
$total_item = $_COOKIE['total_item'];
$shipment_price = $_COOKIE['shipment_price'];
$shipment_way = $_COOKIE['shipment_way'];
$phonesPrice = $_COOKIE['phones_price'];
$totalPrice = $shipment_price + $phonesPrice;
echo "<tr>";
echo "<td>".$total_item."</td>";
echo "<td>".$phonesPrice."</td>";
echo "<td>".$shipment_way."</td>";
echo "<td>".$shipment_price."</td>";
echo "<td>".$totalPrice."</td>";
echo "</tr>";
?>
</table>
<br>
<form action="payway.php" method="post">
<input type="radio" name="payway" value="Alipay" checked="">Alipay <input type="radio" name="payway" value="WeChatPay">WeChatPay <input type="radio" name="payway" value="Credit">Credit card <input type="radio" name="payway" value="UnionPay">UnionPay<br>
<table border = '1'>
<tr>
<th>Pay user</th>
<th>Pay account</th>
<th>Receive user</th>
<th>Receive account</th>
</tr>
<tr>
<th><input type="text" name="payuser"></th>
<th><input type="text" name="payaccount"></th>
<th><input type="text" name="receiveuser"></th>
<th><input type="text" name="receiveaccount"></th>
</tr>
</table>
<input type="submit" value="Submit">
</form><?php
}
?></body></html>界面如图: 
2)pay_way.php
//将用户支付信息填入数据库表中,并跳转到pay_money.php
<?phpfunction executeSql($sql){
$flag = false; $feedback = array(); if($sql == ""){ echo "Error! Sql content is empty!";
}else{ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "hw"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error();
} $query_result=mysqli_query($conn,$sql);//query_result is a PHP array
if($query_result){ $flag = true; $feedback = $query_result; //$num_rows=mysqli_num_rows($query_result);
} return array($flag,$feedback);
}
} $payWay = $_POST['payway']; $payUser = $_POST['payuser']; $payAccount = $_POST['payaccount']; $receiveUser = $_POST['receiveuser']; $receiveAccount = $_POST['receiveaccount']; $payStatus = false; $numbers = range (1,1000000);
shuffle ($numbers);
$num=1;
$result = array_slice($numbers,0,$num);
$pay_random = $result[0]; if($payUser == "" ||$payAccount == "" || $receiveUser == "" || $receiveAccount == ""){ echo "You must fill the blanks.";
}else{ $sql = "INSERT INTO payment_info (pay_user, receive_user, pay_account, receive_account,pay_way,pay_status,pay_random)
VALUES ('".$payUser."', '".$receiveUser."', ".$payAccount.",".$receiveAccount.",'".$payWay."','".$payStatus."',".$pay_random.");"; $result = executeSql($sql); if($result[0]){ $select_sql = "SELECT pay_id FROM payment_info WHERE pay_random = ".$pay_random.";"; $select_result = executeSql($select_sql); if($select_result[0]){ while ($row = mysqli_fetch_assoc($select_result[1])){ $pay_id=$row["pay_id"];
setcookie('pay_id',$pay_id);
}
}
setcookie('pay_way',$payWay);
}
header("location:pay_money.php");
}?>3)pay_money.php
//根据payInfo.php中选择的支付方式,打开相应的界面,让用户登录并付钱。
然后将订单信息全部丢给process_order.php处理
//这里有一点需要特别说明的是,因为这是一个练习,数据都是虚拟的,所以无法从支付宝或者微信,银联等获知用户支付已经支付成功,所以这里将是否已经支付的判定设置为,只要用户填写了付款信息,并点击付款,打开了支付页面,这里就在cookie中设置为已支付状态
<?php
function executeSql($sql){ $flag = false; $feedback = array(); if($sql == ""){ echo "Error! Sql content is empty!";
}else{ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "hw"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error();
} $query_result=mysqli_query($conn,$sql);//query_result is a PHP array if($query_result){ $flag = true; $feedback = $query_result;
//$num_rows=mysqli_num_rows($query_result);
} return array($flag,$feedback);
}
}if(isset($_COOKIE['pay_way'])){ $payWay = $_COOKIE['pay_way'];
}else{ echo "Error!";
}if($payWay == "Alipay"){ echo "<script>window.open('https://auth.alipay.com/login/index.htm?goto=https%3A%2F%2Fmy.alipay.com%2Fportal%2Fi.htm')</script>";
//$image_url = "https://www.hkelectric.com/zh/CustomerServices/PublishingImages/Alipay_Download_QR.jpg";
//$imageData = base64_encode(file_get_contents($image_url));
//echo '<img src="data:image/jpeg;base64,'.$imageData.'">';
}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 '<img src="data:image/jpeg;base64,'.$imageData.'">'; echo "<script>window.open('https://pay.weixin.qq.com/index.php/public/wechatpay')</script>";
}else if($payWay == "Credit"){ echo "<script>window.open('https://bank.hangseng.com/1/2/chi/e-services/personal-ebanking/hk-personal-ebanking')</script>";
}else if($payWay == "UnionPay"){ echo "<script>window.open('https://cn.unionpay.com/front.do')</script>";
}
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 "<br>"; echo "<br>"; echo "<a href='process_order.php'>Click here to see order information.</a>";
}else{ echo "You have to pay first!";
}
?>1)process_order.php
//将订单的信息填入到数据库表中
<!DOCTYPE html>
<html>
<head>
<title>Order information</title>
</head>
<body> <?php
function executeSql($sql){
$flag = false; $feedback = array(); if($sql == ""){ echo "Error! Sql content is empty!";
}else{ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "hw"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error();
} $query_result=mysqli_query($conn,$sql);//query_result is a PHP array
if($query_result){ $flag = true; $feedback = $query_result; //$num_rows=mysqli_num_rows($query_result);
} return array($flag,$feedback);
}
} function infoSplit($p_info){
$result = array(); $single_info = explode("/", $p_info); foreach($single_info as $val){ $single_result = array(); $details = explode(",",$val); foreach ($details as $value){
array_push($single_result, $value);
}
array_push($result, $single_result);
}
array_pop($result); return $result;
} $u_id = $_COOKIE['u_id']; $d_id = $_COOKIE['d_id']; $pay_id = $_COOKIE['pay_id']; $p_info = $_COOKIE['p_info']; echo $p_info; $o_date = date("Y-m-d H:i:s"); $o_id = 0; //echo gettype($o_date);
$sql = "INSERT INTO order_info (u_id,d_id,o_date,pay_id) VALUES(".$u_id.",".$d_id.",'".$o_date."',".$pay_id.");"; $insert_result = executeSql($sql); if($insert_result[0]){ $select_sql = "SELECT o_id FROM order_info WHERE pay_id = ".$pay_id.";"; $select_result = executeSql($select_sql); if($select_result[0]){ while($row = mysqli_fetch_assoc($select_result[1])){ $o_id=$row["o_id"];
setcookie('o_id',$o_id);
}
}
} $split_result = infoSplit($p_info); //var_dump($split_result);
for($i = 0; $i < count($split_result);$i++){ $p_id = $split_result[$i][0]; $p_num = $split_result[$i][1]; $p_inventory = 0; $insert_order_sql = "INSERT INTO orderDetailRecord_info (o_id,p_id,p_num) VALUES(".$o_id.",".$p_id.",".$p_num.");"; $insert_order_result = executeSql($insert_order_sql); if($insert_order_result[0]){ //select product num from stock_info and update
$select_stock_num_sql = "SELECT p_inventory FROM stock_info WHERE p_id = ".$p_id.";"; $select_stock_num_result = executeSql($select_stock_num_sql); if($select_stock_num_result[0]){ while($row = mysqli_fetch_assoc($select_stock_num_result[1])){ $p_inventory = $row['p_inventory'];
}
} //update p_inventory
$p_inventory = $p_inventory - $p_num; $update_sql = "UPDATE stock_info SET p_inventory = '".$p_inventory."' WHERE p_id = '".$p_id."';"; $update_result = executeSql($update_sql); if($update_result[0]){
header('location:view_order.php');
}
}
} ?>
</body>
</html>2)view_order.php
//查看订单信息,并给出生成报告的链接
<!DOCTYPE html>
<html>
<head>
<title>Order Information</title>
</head>
<body> <?php
if($_COOKIE['pay_status']){ $o_id = $_COOKIE['o_id']; $u_id = $_COOKIE['u_id']; $tracking_num = $_COOKIE['d_id']; $pay_id = $_COOKIE['pay_id']; $total_item = $_COOKIE['total_item']; $phones_price = $_COOKIE['phones_price']; $shipment_price = $_COOKIE['shipment_price']; $total_price = $phones_price + $shipment_price; $pay_status = $_COOKIE['pay_status']; ?>
<table border="1">
<caption><h2>Order information</h2></caption>
<tr>
<th>Order id</th>
<th>User</th>
<th>Tracking Number</th>
<th>Product Price</th>
<th>Delivery Price</th>
<th>Total Items</th>
<th>Total Price</th>
<th>Payment ID</th>
<th>Pay Status</th>
</tr> <?php
echo "<tr>"; echo "<td>".$o_id."</td>"; echo "<td>".$u_id."</td>"; echo "<td>".$tracking_num."</td>"; echo "<td>".$phones_price."HKD</td>"; echo "<td>".$shipment_price