聲明!
最近幾個(gè)月,不斷地有站友向我索要完整的代碼,其實(shí)之前我是全部粘貼到博客里供大家參考交流的。之所以刪掉一部分,是因?yàn)橛幸恍┚W(wǎng)站全盤照抄并標(biāo)明為原創(chuàng),以抄襲獲取流量甚至盈利,違背了我的初衷。
感謝各位不嫌棄我的代碼粗陋。如果還有站友想要源代碼,請?jiān)谶@篇博客下留下自己的聯(lián)系方式。但是再次聲明,之前和今后私下從我這里以任何方式要走的代碼,都不能用作商業(yè)用途!
請勿轉(zhuǎn)載!
謝謝!
這是我在研究生期間,老師要求做的一個(gè)類似原始淘寶網(wǎng)的購物網(wǎng)站, 因?yàn)椴粫?huì)PHP,為了寫這個(gè)作業(yè)而新學(xué)的。 做這個(gè)網(wǎng)站用了兩周時(shí)間,在此把這個(gè)小項(xiàng)目做一個(gè)總結(jié)。
這個(gè)小項(xiàng)目做的時(shí)間非常趕,一共兩周,實(shí)際有效時(shí)間只有10天,中間還在忙其他的事。所以有很多不足之處。 有些代碼原本可以寫的更精簡,合并在一起。 連接數(shù)據(jù)庫和其他的一些執(zhí)行sql語句的操作,可以封裝在單獨(dú)的文件里面調(diào)用,這里也都比較簡單的哪里用到就在哪里處理了。 數(shù)據(jù)庫的鏈接方式用了兩種,沒有統(tǒng)一。
還是有很多值得改進(jìn)的地方。
功能:
DONE. 用戶權(quán)限管理。包括管理員和普通用戶。管理員有所有權(quán)限,包括更新網(wǎng)站狀態(tài) 登錄的其他值為用戶名和密碼,用戶名和密碼正確,跳轉(zhuǎn)到下一頁。 ADMIN具有添加,刪除,更新等權(quán)限。用戶只能查看手機(jī),只能添加到購物車中的手機(jī)等。
DONE.新用戶:此模塊適用于沒有帳戶的用戶。這里用戶可以創(chuàng)建一個(gè)帳戶來登錄。賬戶的創(chuàng)建是通過填寫注冊表單和用戶的詳細(xì)信息,如姓名,電話,電子郵件等來完成的。
DONE.產(chǎn)品管理和展示:該模塊展示手機(jī)產(chǎn)品信息,如產(chǎn)品編號(hào),項(xiàng)目,名稱,類別,產(chǎn)品圖像,說明,功能和產(chǎn)品限制等。所有這些都將輸入到數(shù)據(jù)庫,因此可以在網(wǎng)站上找到。
DONE.搜索:該模塊可幫助客戶根據(jù)自己的預(yù)算或興趣來放松搜索。搜索可以在不同的類別上完成,如品牌,型號(hào)名稱,型號(hào),顏色或價(jià)格等。
DONE:交易:在此模塊中,購物車的管理已完成。此模塊購物者可以選擇任意數(shù)量的物品(手機(jī),配件)并將它們添加到購物車,在從購物車購買物品后,所有要購買的物品都可以再次查看。如果他以后不喜歡,購物者也可以從購物車中取出。購物者還可以逐一檢查購物車中保存的產(chǎn)品。由于產(chǎn)品從購物車中檢出,總價(jià)格將相加。
DONE:裝運(yùn):在這個(gè)模塊中,購物者可以選擇合適的裝運(yùn)選項(xiàng)。購物者可以使用不同服務(wù)提供商提供的各種運(yùn)送選項(xiàng)。
DONE:付款:該模塊描述了客戶完成的付款。購物者可以選擇不同的支付方式,并根據(jù)所選的支付方式的要求提供機(jī)密的支付信息。付款信息還可能包括購買型號(hào),數(shù)量和供應(yīng)商名稱等信息。
DONE:報(bào)告:在此模塊中,將生成所有報(bào)告。無論何時(shí)出售物品或客戶訂購產(chǎn)品,都應(yīng)立即通過電子郵件向其供應(yīng)商發(fā)送警報(bào),以便他可以盡快裝運(yùn)該物品。該模塊有3個(gè)子模塊;股票報(bào)告,訂單報(bào)告和交付報(bào)告。
股票報(bào)告將生成可用產(chǎn)品數(shù)量和產(chǎn)品狀態(tài)的報(bào)告。 訂單報(bào)告將列出訂購的產(chǎn)品清單以及購買該產(chǎn)品的客戶詳細(xì)信息,這些信息未送達(dá)。 交付報(bào)告將生成已售出產(chǎn)品清單及其交付狀態(tài)。
###1.數(shù)據(jù)庫表設(shè)計(jì) 下面是對數(shù)據(jù)庫設(shè)計(jì)的一個(gè)說明,交作業(yè)用的。
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表中分別加入了一個(gè)random字段,是因?yàn)樵趯憄hp處理的過程中,產(chǎn)生了相應(yīng)的需要,具體處理請看代碼。
下面是具體的表名和字段:
附上剛開始創(chuàng)建數(shù)據(jù)表的mysql代碼,后期自此基礎(chǔ)上有一些修改
`admin_info(admin_id,admin_name,admin_pwd)`
CREATE TABLE IF NOT EXISTS admin_info(admin_id int(10) NOT NULL AUTO_INCREMENT,admin_name varchar(50) NOT NULL,admin_pwd varchar(50) NOT NULL,PRIMARY KEY(admin_id)
);`user_info(u_id,u_name,u_pwd,u_phone,u_email)`
CREATE TABLE IF NOT EXISTS user_info(u_id int(10) NOT NULL AUTO_INCREMENT,u_name varchar(50) NOT NULL,u_pwd varchar(50) NOT NULL,u_phone int(50) NOT NULL,u_email varchar(50) NOT NULL,PRIMARY KEY(u_id)
);`product_info(p_id, p_name,p_brand, p_type,p_price,p_inventory,p_descr,p_color,p_image_url)`
CREATE TABLE IF NOT EXISTS product_info(p_id int(10) NOT NULL AUTO_INCREMENT,p_name varchar(50) NOT NULL,p_brand varchar(50) NOT NULL,p_type int(50) NOT NULL,p_price varchar(50) NOT NULL,p_inventory varchar(50) NOT NULL,p_descr varchar(100) NOT NULL,p_color varchar(50) NOT NULL,p_image_url varchar(200) NOT NULL,PRIMARY KEY(p_id)
);`payment_info(pay_id,pay_user,receive_user,pay_account,receive_account,pay_status)`
CREATE TABLE IF NOT EXISTS payment_info(pay_id int(10) NOT NULL AUTO_INCREMENT,pay_user varchar(50) NOT NULL,receive_user varchar(50) NOT NULL,pay_account int(50) NOT NULL,receive_account int(50) NOT NULL,pay_status boolean NOT NULL,PRIMARY KEY(pay_id)
);`delivery_info(d_id,d_company,d_init_add,d_trgt_add,d_price)`
CREATE TABLE IF NOT EXISTS delivery_info(d_id int(10) NOT NULL AUTO_INCREMENT,d_company varchar(50) NOT NULL,d_init_add varchar(50) NOT NULL,d_trgt_add varchar(50) NOT NULL,d_price varchar(50) NOT NULL,PRIMARY KEY(d_id)
);`order_info(o_id,u_id,d_id,o_date,pay_id)`
CREATE TABLE IF NOT EXISTS order_info(o_id int(10) NOT NULL AUTO_INCREMENT,u_id int NOT NULL,d_id int NOT NULL,o_date int(50) NOT NULL,pay_id int NOT NULL,PRIMARY KEY(o_id),FOREIGN KEY (u_id) REFERENCES user_info(u_id),FOREIGN KEY (d_id) REFERENCES delivery_info(d_id),FOREIGN KEY (pay_id) REFERENCES payment_info(pay_id)
);`orderDetailRecord_info(r_id,o_id,p_id,p_num)`
CREATE TABLE IF NOT EXISTS orderDetailRecord_info(r_id int(10) NOT NULL AUTO_INCREMENT,o_id int NOT NULL,p_id int NOT NULL,p_num int(50) NOT NULL,PRIMARY KEY(r_id),FOREIGN KEY (o_id) REFERENCES order_info(o_id),FOREIGN KEY (p_id) REFERENCES product_info(p_id)
);`stock_info(s_id,p_id,p_inventory)`
CREATE TABLE IF NOT EXISTS stock_info(s_id int(10) NOT NULL AUTO_INCREMENT,p_id int(10),p_inventory int(50),PRIMARY KEY(s_id),FOREIGN KEY(p_id) REFERENCES product_info(p_id)
);
下面是以上功能的代碼以及一些相關(guān)的解釋: 最簡單的主界面: index.html //只放了一個(gè)注冊一個(gè)登錄的鏈接
<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>
###1.注冊功能: 首先要選擇角色類型:(這個(gè)功能是剛開始練習(xí)做的,其實(shí)應(yīng)該把角色選擇和注冊功能都放在一個(gè)頁面里,現(xiàn)在分為了三個(gè),分別是選擇,管理員注冊和用戶注冊,比較麻煩。后來時(shí)間緊,就沒有再改了,實(shí)際可以合并為一個(gè)。)
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 //選擇相應(yīng)的角色后,會(huì)跳轉(zhuǎn)到不同角色的注冊界面
<!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 //管理員注冊的界面。管理員注冊需要拿到內(nèi)部的Invitation number(邀請碼),注冊方可進(jìn)行。如果已經(jīng)注冊,可以點(diǎn)擊下方的login鏈接,直接登錄,將跳轉(zhuǎn)到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><?phpinclude '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 //處理用戶注冊請求,收集基本信息并加入到數(shù)據(jù)庫。如果存在數(shù)據(jù)缺失,則不能注冊,對兩次輸入的密碼做了基本的檢測,并檢測郵箱格式的正確性。 //注冊后會(huì)跳轉(zhuǎn)到login.php界面,但是因?yàn)槠胀ㄓ脩糇院?#xff0c;會(huì)自動(dòng)為當(dāng)前用戶登錄,并在當(dāng)前的cookie中存儲(chǔ)用戶登錄的狀態(tài),因此不需要再登錄一次,可以直接由網(wǎng)頁鏈接跳轉(zhuǎn)到手機(jī)購買界面。
<!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;}/*.divcss5-right{width:320px; height:120px;border:1px solid #F00;float:right} */.divcss5-right{float:right;} /* css注釋:對divcss5-right設(shè)置float:right即可讓對象靠右浮動(dòng) */</style>
</head>
<body><?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 arrayif($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>
###2.登錄功能: login.php //用戶登錄的界面,可以選擇管理員用戶登錄和普通用戶登錄。 作為管理員用戶登錄后,跳轉(zhuǎn)到產(chǎn)品管理界面。作為普通用戶登錄后,跳轉(zhuǎn)到網(wǎng)站主頁,即手機(jī)購買界面。
<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"><?phpif(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><?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 arrayif($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>
###3.手機(jī)產(chǎn)品管理(管理員): 1)增加新的手機(jī): add_product.html //增加新的手機(jī)庫存
<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><?phpfunction executeSql($sql){$flag = false;if($sql == ""){echo "Error! Sql content is empty!";echo "<br>";}else{$servername = "localhost";$username = "root";$password = "";$dbname = "hw";// 創(chuàng)建連接$conn = new mysqli($servername, $username, $password, $dbname);// 檢測連接if ($conn->connect_error) {die("Fail to connect!: " . $conn->connect_error);}//執(zhí)行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";// 創(chuàng)建連接$conn = mysqli_connect($servername, $username, $password, $dbname);// Check connectionif (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 arrayvar_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)管理員管理手機(jī)(查看,刪除,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;} /* 鼠標(biāo)移動(dòng)到鏈接上 */a:active {color:#0000FF;} /* 鼠標(biāo)點(diǎn)擊時(shí) */</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";// 創(chuàng)建連接$conn = mysqli_connect($servername, $username, $password, $dbname);// Check connectionif (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 '<div class="img">';echo '<td align="center">[外鏈圖片轉(zhuǎn)存失敗(img-WDPS9q7a-1562059529495)(data:image/jpeg;base64,'.$imageData.')]</td>';//echo '</div>';//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><?phpecho "</tr>";$i++;}mysqli_close($conn);?></table><br><br><div class="divcss5-right"><input type="button" class = "button" value="Add new product" onclick="newPage()"></div>
</body>
</html>
界面如圖所示(縮小版的界面)
4.用戶購買手機(jī)
手機(jī)展示界面,并可實(shí)現(xiàn)增加產(chǎn)品到購物車,沒有實(shí)現(xiàn)批量添加,每點(diǎn)擊一次手機(jī)產(chǎn)品對應(yīng)的添加按鈕,則購物車中增加一條該產(chǎn)品的記錄。 添加后會(huì)在購物車功能模塊處理,如果已經(jīng)添加夠了,也可以直接點(diǎn)擊頁面最下方的鏈接,查看購物車。
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;} /* 鼠標(biāo)移動(dòng)到鏈接上 */a:active {color:#0000FF;} /* 鼠標(biāo)點(diǎn)擊時(shí) */</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";// 創(chuàng)建連接$conn = mysqli_connect($servername, $username, $password, $dbname);// Check connectionif (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">[外鏈圖片轉(zhuǎn)存失敗(img-ePhuvnsp-1562059529496)(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>
<?phpecho "</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>
###5.購物車 1)process_shopCart.php//處理添加請求
<!DOCTYPE html>
<html>
<head><title>All fees of shipment.</title>
</head>
<body><?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 arrayif($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 將數(shù)組順序隨即打亂 shuffle ($numbers); //array_slice 取該數(shù)組中的某一段 $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><?phpecho "</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><?phpecho "".$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>
購物車如下圖:
購物車中會(huì)展示所有產(chǎn)品的信息,并計(jì)算他們的總價(jià)格。
3)delCart.php //如果用戶在查看購物車時(shí)點(diǎn)擊刪除某項(xiàng)產(chǎn)品,將該產(chǎn)品從購物車中全部刪除
<?php
session_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]){//如果存在該項(xiàng),從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 //如果用戶在查看購物車時(shí),點(diǎn)擊了清空購物車,將當(dāng)前購物車中內(nèi)容全部清空
<?php
session_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");
?>
###6.物流 點(diǎn)擊購物車中的’shipment’,選擇裝運(yùn)物流信息。 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><?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 arrayif($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 將數(shù)組順序隨即打亂 shuffle ($numbers); //array_slice 取該數(shù)組中的某一段 $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>
物流選擇界面如圖:
###7.支付 1)payInfo.php //計(jì)算商品和物流的總價(jià)格并展示,讓用戶選擇支付方式。如果已經(jīng)選擇了支付方式(檢查cookie中的值),提升已經(jīng)選擇,并且給出跳轉(zhuǎn)動(dòng)支付頁面的鏈接。否則讓用戶選擇支付方式,提供了四種,微信,支付寶,信用卡和中國銀聯(lián),默認(rèn)選項(xiàng)為支付寶
<html>
<head><meta charset="utf-8"><title>Shop cart</title>
</head>
<h1>Total money here, please fill your payment information.</h1>
<body><?phpif(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 //將用戶支付信息填入數(shù)據(jù)庫表中,并跳轉(zhuǎn)到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 arrayif($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 //根據(jù)payInfo.php中選擇的支付方式,打開相應(yīng)的界面,讓用戶登錄并付錢。 然后將訂單信息全部丟給process_order.php處理 //這里有一點(diǎn)需要特別說明的是,因?yàn)檫@是一個(gè)練習(xí),數(shù)據(jù)都是虛擬的,所以無法從支付寶或者微信,銀聯(lián)等獲知用戶支付已經(jīng)支付成功,所以這里將是否已經(jīng)支付的判定設(shè)置為,只要用戶填寫了付款信息,并點(diǎn)擊付款,打開了支付頁面,這里就在cookie中設(shè)置為已支付狀態(tài)
<?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 arrayif($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 '[外鏈圖片轉(zhuǎn)存失敗(img-0UVbanjU-1562059529497)(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 '[外鏈圖片轉(zhuǎn)存失敗(img-Ji9HZKJS-1562059529497)(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!";
}?>
###8.查看交易信息并導(dǎo)出報(bào)告 1)process_order.php //將訂單的信息填入到數(shù)據(jù)庫表中
<!DOCTYPE html>
<html>
<head><title>Order information</title>
</head>
<body><?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 arrayif($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 //查看訂單信息,并給出生成報(bào)告的鏈接
<!DOCTYPE html>
<html>
<head><title>Order Information</title>
</head>
<body><?phpif($_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><?phpecho "<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."HKD</td>";echo "<td>".$total_item."</td>";echo "<td>".$total_price."HKD</td>";echo "<td>".$pay_id."</td>";if($pay_status){echo "<td>Paid</td>";}else{echo "<td>Not Paid</td>";}echo "</tr>";echo "</table>";echo "<br>";echo "<a href='eStockReport.php'>Export Product Report</a>";echo "<br>";echo "<br>";echo "<a href='eOrderReport.php'>Export Order Report</a>";echo "<br>";echo "<br>";echo "<a href='eDeliveryReport.php'>Export Delivery Report</a>";}else{header('location:payInfo.php');}?></body></html>
9.導(dǎo)出報(bào)告
1)eOrderReport.php //導(dǎo)出訂單報(bào)告
<!DOCTYPE html>
<html>
<head><title>Export Report</title>
</head>
<body><?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 arrayif($query_result){$flag = true;$feedback = $query_result;//$num_rows=mysqli_num_rows($query_result);}return array($flag,$feedback);mysqli_close($conn);}}$myfile = fopen("OrderReport.txt", "w")or die("Unable to open file!");$file_stream = null;$sql = "SELECT * FROM order_info;";$result = executeSql($sql);if($result[0]){$i=0;while ($row = mysqli_fetch_assoc($result[1])){$o_id=$row["o_id"];$u_id=$row["u_id"];$d_id=$row["d_id"];$o_date=$row["o_date"];$pay_id=$row["pay_id"];$file_stream = $file_stream."Order ID: ".$o_id."\n";$file_stream = $file_stream."User ID: ".$u_id."\n";$file_stream = $file_stream."Delivery ID: ".$d_id."\n";$file_stream = $file_stream."Order Date: ".$o_date."\n";$file_stream = $file_stream."Payment ID: ".$pay_id."\n";$select_sql = "SELECT * FROM orderDetailRecord_info WHERE o_id = ".$o_id.";";$select_result=executeSql($select_sql);if($select_result[0]){$j = 0;while($select_rows = mysqli_fetch_assoc($select_result[1])){$r_id=$select_rows["r_id"];$p_id=$select_rows["p_id"];$p_num=$select_rows["p_num"];$file_stream = $file_stream."Product ID: ".$p_id." \t";$file_stream = $file_stream."Product Number: ".$p_num."\n";$j++;}}else{echo "not fetch";}$i++;$file_stream = $file_stream."\n\n\n";}}//向文件中寫入字符串fwrite($myfile, $file_stream);//關(guān)閉文件句柄fclose($myfile);header('location:view_order.php');?>
</body>
</html>
2)eStockReport.php //導(dǎo)出庫存報(bào)告
<!DOCTYPE html>
<html>
<head><title>Export Report</title>
</head>
<body><?php$file_stream = null;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 arrayif($query_result){$flag = true;$feedback = $query_result;//$num_rows=mysqli_num_rows($query_result);}return array($flag,$feedback);mysqli_close($conn);}}$myfile = fopen("StockReport.txt", "w")or die("Unable to open file!");$sql = "SELECT * FROM product_info;";$result = executeSql($sql);if($result[0]){$i=0;while ($row = mysqli_fetch_assoc($result[1])){$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=executeSql($select_sql);if($select_result[0]){while($select_rows = mysqli_fetch_assoc($select_result[1])){$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"];//$imageData = base64_encode(file_get_contents($p_image_url));$file_stream = $file_stream."Product ID: ".$p_id."\n";$file_stream = $file_stream."Product Name: ".$p_name."\n";$file_stream = $file_stream."Product Brand: ".$p_brand."\n";$file_stream = $file_stream."Product Type: ".$p_type."\n";$file_stream = $file_stream."Product Price: ".$p_price."\n";$file_stream = $file_stream."Product Inventory: ".$p_inventory."\n";$file_stream = $file_stream."Product Description: ".$p_descr."\n";$file_stream = $file_stream."Product Color: ".$p_color."\n";$file_stream = $file_stream."Product Image URL: ".$p_image_url."\n\n\n";$i++;}}//向文件中寫入字符串fwrite($myfile, $file_stream);//關(guān)閉文件句柄fclose($myfile);function php_sendmail($stream){require('class.phpmailer.php'); //$mail->Host = "ssl://smtp.gmail.com";
$mail = new PHPMailer(); //實(shí)例化 $mail->IsSMTP(); // 啟用SMTP //$mail->Host = "smtp.163.com"; //SMTP服務(wù)器 163郵箱例子
$mail->Host = "smtp.126.com"; //SMTP服務(wù)器 126郵箱例子
//$mail->Host = "smtp.qq.com"; //SMTP服務(wù)器 qq郵箱例子 $mail->Port = 25; //郵件發(fā)送端口
$mail->SMTPAuth = true; //啟用SMTP認(rèn)證 $mail->CharSet = "UTF-8"; //字符集
$mail->Encoding = "base64"; //編碼方式 $mail->Username = ""; //你的郵箱
$mail->Password = ""; //你的密碼
$mail->Subject = "Product information updating"; //郵件標(biāo)題 $mail->From = ""; //發(fā)件人地址(也就是你的郵箱)
$mail->FromName = ""; //發(fā)件人姓名 $address = "";//收件人email
$mail->AddAddress($address, ""); //添加收件人1(地址,昵稱) //$mail->AddAttachment('xx.xls','我的附件.xls'); // 添加附件,并指定名稱 $mail->IsHTML(true); //支持html格式內(nèi)容
//$mail->AddEmbeddedImage("logo.jpg", "my-attach", "logo.jpg"); //設(shè)置郵件中的圖片
$mail->Body = $file_stream; //郵件主體內(nèi)容 //發(fā)送
if(!$mail->Send()){ echo "Fialed to send " . $mail->ErrorInfo;
} else { echo "Successfully send the email!";
}
}php_sendmail($file_stream);
header('location:view_order.php');
?>
</body>
</html>
3)eDeliveryReport.php //導(dǎo)出物流報(bào)告
<!DOCTYPE html>
<html>
<head><title>Export Report</title>
</head>
<body><?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 arrayif($query_result){$flag = true;$feedback = $query_result;//$num_rows=mysqli_num_rows($query_result);}return array($flag,$feedback);mysqli_close($conn);}}$myfile = fopen("DeliveryReport.txt", "w")or die("Unable to open file!");$file_stream = null;$sql = "SELECT * FROM delivery_info;";$result = executeSql($sql);if($result[0]){$i=0;while ($row = mysqli_fetch_assoc($result[1])){$d_id=$row["d_id"];$d_company=$row["d_company"];$d_init_add=$row["d_init_add"];$d_trgt_add=$row["d_trgt_add"];$d_price=$row["d_price"];$file_stream = $file_stream."Delivery ID: ".$d_id."\n";$file_stream = $file_stream."Delivery Company: ".$d_company."\n";$file_stream = $file_stream."Delivery Initial Address: ".$d_init_add."\n";$file_stream = $file_stream."Delivery Target Address: ".$d_trgt_add."\n";$file_stream = $file_stream."Delivery Price: ".$d_price."\n\n\n";$i++;}}//向文件中寫入字符串fwrite($myfile, $file_stream);//關(guān)閉文件句柄fclose($myfile);header('location:view_order.php');?>
</body>
</html>
###10.搜索功能 做了一個(gè)分類搜索的功能,用的就是數(shù)據(jù)庫的模糊查詢,很簡單 1)search.html //頁面
<html>
<head>
<meta charset="utf-8">
<title>Search phones</title>
</head>
<h1>Search what you want</h1><form action="search.php" method="post"><select name="select_condition"><option value="">Choose a condition</option><option value="brand">Brand</option><option value="name">Product Name</option><option value="type">Type</option><option value="color">Color</option><option value="price">Price</option></select><br><br>Enter your condition here:<br><input type="text" name="value"><br><br>If you choose price, please enter the price range here:<br>Low range:<input type="text" name="low_range"><br>High range:<input type="text" name="high_range"><br><input type="submit" name="submit" value="Submit"></form>
</html>
2)search.php //處理查詢請求
<!DOCTYPE html>
<html>
<body>
<?phpif(isset($_POST["submit"])){$selected_Condition = $_POST["select_condition"];}else{echo "No condition selected!";echo "<br>";}if($selected_Condition == "brand"){$value = $_POST["value"];if($value ==""){echo "The value can't be empty!";echo "<br>";}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 "<br>";}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 "<br>";}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 "<br>";}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 "<br>";}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 connectionif (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 '<table border="1">';echo "<tr>";echo "<th>Product Name</th>";echo "<th>Product Brand</th>";echo "<th>Product Type</th>";echo "<th>Product Price</th>";echo "<th>Product Description</th>";echo "<th>Product Color</th>";echo "<th>Product Image</th>";echo "</tr>";$i=0;while ($row = mysqli_fetch_assoc($result)){$p_name=$row["p_name"];$p_brand=$row["p_brand"];$p_type=$row["p_type"];$p_price=$row["p_price"];$p_descr=$row["p_descr"];$p_color=$row["p_color"];$p_image_url = $row["p_image_url"];echo "<tr>";echo "<td>".$p_name."</td>";echo "<td>".$p_brand."</td>";echo "<td>".$p_type."</td>";echo "<td>".$p_price."</td>";echo "<td>".$p_descr."</td>";echo "<td>".$p_color."</td>";$imageData = base64_encode(file_get_contents($p_image_url));echo '<td>[外鏈圖片轉(zhuǎn)存失敗(img-CAzDYQv5-1562059529498)(data:image/jpeg;base64,'.$imageData.')]</td>';echo "</tr>";$i++;}echo "</table>";}}?></body>
</html>
####特別說明: 1)購物車用session實(shí)現(xiàn) 2)其他各種用戶登錄狀態(tài),產(chǎn)品id等信息,均存儲(chǔ)在cookie數(shù)組中 3)當(dāng)某種產(chǎn)品賣出后,會(huì)從數(shù)據(jù)庫中將該產(chǎn)品的庫存減去訂單中相應(yīng)的數(shù)量。
總結(jié)
以上是生活随笔 為你收集整理的PHP购物网站(含购物车、全部源码、数据库设计表及其源码) 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。