>백엔드 개발 >PHP 튜토리얼 >PHP는 쇼핑 웹사이트를 구현합니다.

PHP는 쇼핑 웹사이트를 구현합니다.

不言
不言원래의
2018-04-24 16:05:3421599검색

이 글의 내용은 PHP로 쇼핑 웹사이트를 구현하는 내용입니다. 이제는 모든 사람과 공유합니다. 도움이 필요한 친구들이 참고할 수 있습니다.

这是我在研究生期间,老师要求做的一个类似原始淘宝网的购物网站,因为不会PHP,为了写这个作业而新学的。做这个网站用了两周时间,在此把这个小项目做一个总结。

기능:

DONE. . 관리자 및 일반 사용자를 포함합니다. 관리자는 웹사이트 상태 업데이트를 포함한 모든 권한을 가집니다.
로그인에 대한 다른 값은 사용자 이름과 비밀번호가 올바른 경우 다음 페이지로 이동합니다.
ADMIN은 추가, 삭제, 업데이트 등의 권한을 가지고 있습니다. 사용자는 휴대폰을 볼 수만 있고 장바구니에 휴대폰을 추가할 수만 있습니다.

완료. 신규 사용자: 이 모듈은 계정이 없는 사용자를 위한 것입니다. 여기서 사용자는 로그인을 위한 계정을 생성할 수 있습니다. 계정 생성은 이름, 전화번호, 이메일 등 사용자 정보를 등록 양식에 작성하여 수행됩니다.

DONE. 제품 관리 및 표시: 이 모듈은 제품 번호, 품목, 이름, 카테고리, 제품 이미지, 설명, 기능 및 제품 제한 사항 등 휴대폰 제품 정보를 표시합니다. 이 모든 내용은 데이터베이스에 입력되어 웹사이트에서 찾을 수 있습니다.

DONE.Search: 이 모듈은 고객이 예산이나 관심 사항에 따라 검색을 쉽게 할 수 있도록 도와줍니다. 브랜드, 모델명, 모델번호, 색상, 가격 등 다양한 카테고리로 검색할 수 있습니다.

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>

1 등록 기능:

먼저 역할 유형을 선택하려면: (이 기능은 처음에만 연습했습니다. 실제로 역할 선택 및 등록 기능은 한 페이지에 배치되어야 합니다. 이제는 선택, 관리자 등록, 사용자 등록의 세 가지로 나누어져 있습니다. 나중에는 시간이 촉박해서 더 이상 바꾸지 않았어요. 실제로 하나로 병합할 수도 있었죠.)

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[&#39;q&#39;])? htmlspecialchars($_GET[&#39;q&#39;]) : &#39;&#39;;
           if($q == "") {
                echo "You must choose a charactor!";
            }else if($q != ""){
                if($q ==&#39;admin&#39;) {
                    header(&#39;Location: adminSign.html&#39;);
                } else if($q ==&#39;user&#39;) {
                    header(&#39;Location: sign.html&#39;);
                }
            }
    ?></body></html>

1 )관리자 등록:
adminSign.html
//관리자 등록 인터페이스. 관리자 등록을 진행하려면 내부 초대번호(초대코드)가 필요합니다. 이미 등록한 경우 아래 로그인 링크를 클릭하여 직접 로그인하면 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 &#39;executeSql.php&#39;;        $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(&#39;" . $userName . "&#39;,&#39;" . $pwd . "&#39;);";
            //$sql = "INSERT INTO admin_info (admin_name,admin_pwd) VALUES(&#39;superadmin&#39;,&#39;admin123&#39;);";
            //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 인터페이스로 이동하게 됩니다. 그러나 일반 사용자가 등록한 후에는 현재 사용자에 대해 자동으로 로그인되고 사용자의 로그인 상태가 현재 쿠키에 저장됩니다. 다시 로그인하시면 됩니다. 웹링크는 모바일 구매 인터페이스로 이동합니다.

<!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(&#39;" .$userName ."&#39;,&#39;" . $pwd ."&#39;,&#39;" . $phone . "&#39;,&#39;" . $email . "&#39;);";        $result = executeSql($sql);
        if($result){            $select_sql = "SELECT u_id FROM user_info WHERE u_name = &#39;".$userName."&#39;;";            $result = executeSql($select_sql);
            if($result[0]){
                setcookie(&#39;login_status&#39;,true);
                while($row = mysqli_fetch_assoc($result[1])){                    $u_id=$row["u_id"];
                    setcookie(&#39;u_id&#39;,$u_id);
                }
                header("location:login.php");
            }
        }
    }
    ?></body></html>

2. 로그인 기능:

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[&#39;login_status&#39;])){
            echo "Login already.";
        ?>
        <br>
        <br>
        <a href=&#39;showPhones.php&#39;>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 = &#39;" . $userName . "&#39; and admin_pwd = &#39;". $pwd ." &#39; ;" ;        $result = executeSql($sql);
        if ($result[0]) {
            header(&#39;Location: p_manage.php&#39;);
        } 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 = &#39;" . $userName ."&#39; and u_pwd = &#39;".$pwd."&#39; ;" ;        $result = executeSql($sql);

        if($result[0]){
            setcookie(&#39;login_status&#39;,true);
            while ($row = mysqli_fetch_assoc($result[1])){                    $u_id=$row["u_id"];
                    setcookie(&#39;u_id&#39;,$u_id);
            }
            header(&#39;Location: showPhones.php&#39;);
        }else{
            echo "Error! Something wrong in your username or password!";
            echo "<br>";
        }
    }
    ?></body></html>

3. 휴대폰 제품 관리(관리자):

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 
        (&#39;".$p_name."&#39;,&#39;".$p_brand."&#39;,&#39;".$p_type."&#39;,&#39;".$p_price."&#39;,&#39;".$p_descr."&#39;,&#39;".$p_color."&#39;,&#39;".$p_image_url."&#39;);";        $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 = &#39;".$p_name."&#39;;";            $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=&#39;center&#39;>".$p_id."</td>";
            echo "<td align=&#39;center&#39;>".$p_name."</td>";
            echo "<td align=&#39;center&#39;>".$p_brand."</td>";
            echo "<td align=&#39;center&#39;>".$p_type."</td>";
            echo "<td align=&#39;center&#39;>".$p_price."</td>";
            echo "<td align=&#39;center&#39;>".$p_inventory."</td>";
            echo "<td align=&#39;center&#39;>".$p_descr."</td>";
            echo "<td align=&#39;center&#39;>".$p_color."</td>";

            //$image = &#39;https://cdn2.gsmarena.com/vv/pics/apple/apple-iphone-x-new-1.jpg&#39;;            $imageData = base64_encode(file_get_contents($p_image_url));
            //var_dump($imageData);
            //echo &#39;<p class="img">&#39;;
            echo &#39;<td align="center"><img src="data:image/jpeg;base64,&#39;.$imageData.&#39;" alt="Forest" width="120"    style="max-width:90%"></td>&#39;;
            //echo &#39;</p>&#39;;
            //echo "<td><input type=&#39;button&#39; value=&#39;Delete&#39; onclick=&#39;deleteProduct(".$p_id.")&#39;></td>";
            ?>
            <td align="center"><a href=&#39;deleteProduct.php?goods_id=<?php echo $p_id; ?>&#39;>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>

界面如图所示(缩小版的界面)
PHP는 쇼핑 웹사이트를 구현합니다.

4.用户购买手机

手机展示界面,并可实现增加产品到购物车,没有实现批量添加,每点击一次手机产品对应的添加按钮,则购物车中增加一条该产品的记录。
添加后会在购物车功能模块处理,如果已经添加够了,也可以直接点击页面最下方的链接,查看购物车。

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=&#39;center&#39;>Welcome! You can buy your own phone here.</h2><body class="body">
    <table border="1" class="table"  align=&#39;center&#39;>
        <tr>
            <th align=&#39;center&#39; width="10%">Product Name</th>
            <th align=&#39;center&#39; width="10%">Product Brand</th>
            <th align=&#39;center&#39; width="10%">Product Type</th>
            <th align=&#39;center&#39; width="10%">Product Price</th>
            <th align=&#39;center&#39; width="10%">Product Inventory</th>
            <th align=&#39;center&#39; width="10%">Product Description</th>
            <th align=&#39;center&#39; width="10%">Product Color</th>
            <th align=&#39;center&#39; width="10%">Product Image</th>
            <th align=&#39;center&#39; 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=&#39;center&#39;>".$p_name."</td>";
            echo "<td align=&#39;center&#39;>".$p_brand."</td>";
            echo "<td align=&#39;center&#39;>".$p_type."</td>";
            echo "<td align=&#39;center&#39;>".$p_price."</td>";
            echo "<td align=&#39;center&#39;>".$p_inventory."</td>";
            echo "<td align=&#39;center&#39;>".$p_descr."</td>";
            echo "<td align=&#39;center&#39;>".$p_color."</td>";

            //$image = &#39;https://cdn2.gsmarena.com/vv/pics/apple/apple-iphone-x-new-1.jpg&#39;;            $imageData = base64_encode(file_get_contents($p_image_url));
            //var_dump($imageData);
            echo &#39;<td align="center"><img  src="data:image/jpeg;base64,&#39;.$imageData.&#39;" alt="PHP는 쇼핑 웹사이트를 구현합니다." ></td>&#39;;
?>

            <td><a  align=&#39;center&#39; href=&#39;process_shopCart.php?goods_id=<?php echo $p_id; ?>&goods_name=<?php echo $p_name; ?>&#39;>addCart</a></td><?php

            echo "</tr>";            $i++;
        }
        mysqli_close($conn);
?>
    </table>
    <br><br>
    <a  align=&#39;right&#39; href=&#39;view_shopCart.php&#39;>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>    <?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[&#39;total_item&#39;];        $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 (&#39;".$company."&#39;, &#39;".$orignLocation."&#39;, &#39;".$targetLocation."&#39;,".$shipmentPrice.",".$d_random.");";        $result = executeSql($sql);        if($result[0]){
            setcookie(&#39;shipment_price&#39;,$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(&#39;d_id&#39;,$d_id);
                    setcookie(&#39;shipment_status&#39;,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[&#39;shop-cart&#39;])){
            foreach ($_SESSION[&#39;shop-cart&#39;] 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=&#39;delCart.php?goods_id=<?php echo $p_id; ?>&#39;>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(&#39;p_info&#39;,$p_info);
        ?>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td><a href=&#39;clearCart.php?goods_id=<?php echo $p_id; ?>&#39;>Clear cart</a></td>
            <td>
                <?php
                echo "".$totalItem."   Items. ";
                echo "Totol prize: ".$totalPrice." HKD";
                ?>
            </td>
        </tr>
    </table>
    <br>
    <a href=&#39;shipment.php&#39;>Shipment</a>
    <br>
    <?php
}else{
    echo "The shop cart is empty!";
    ?>
    <br><br>
    <a href=&#39;showPhones.php&#39;>Back to add goods</a>
    <?php
}
?></body></html>

购物车如下图:
PHP는 쇼핑 웹사이트를 구현합니다.

购物车中会展示所有产品的信息,并计算他们的总价格。

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[&#39;shop-cart&#39;]);if($result[0]){    //如果存在该项,从session中删除
    if(isset($result[1])){        unset($_SESSION[&#39;shop-cart&#39;][$result[1]]);        $_SESSION[&#39;shop-cart&#39;] = array_values($_SESSION[&#39;shop-cart&#39;]);
    }
}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[&#39;shop-cart&#39;])){    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.物流

点击购物车中的’shipment’,选择装运物流信息。
shipment.php

<html><head>
    <meta charset="utf-8">
    <title>Shipment</title></head><?php
if(isset($_COOKIE[&#39;shipment_status&#39;])){
?><h1>You have already fill the shipment information</h1><body><a href=&#39;payInfo.php&#39;>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[&#39;total_item&#39;];        $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 (&#39;".$company."&#39;, &#39;".$orignLocation."&#39;, &#39;".$targetLocation."&#39;,".$shipmentPrice.",".$d_random.");";        $result = executeSql($sql);

        if($result[0]){
            setcookie(&#39;shipment_price&#39;,$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(&#39;d_id&#39;,$d_id);
                    setcookie(&#39;shipment_status&#39;,true);
                }
            }
        }
    }
    header("location:payInfo.php");
    ?></body></html>

物流选择界面如图:
PHP는 쇼핑 웹사이트를 구현합니다.

7.支付

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[&#39;pay_way&#39;])){
        echo "You have fill the payment information.";
    ?>
    <br>
        <a href=&#39;pay_money.php&#39;>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[&#39;total_item&#39;];
        $shipment_price = $_COOKIE[&#39;shipment_price&#39;];
        $shipment_way = $_COOKIE[&#39;shipment_way&#39;];
        $phonesPrice = $_COOKIE[&#39;phones_price&#39;];
        $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 = &#39;1&#39;>
            <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>

界面如图:
PHP는 쇼핑 웹사이트를 구현합니다.

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[&#39;payway&#39;];    $payUser = $_POST[&#39;payuser&#39;];    $payAccount = $_POST[&#39;payaccount&#39;];    $receiveUser = $_POST[&#39;receiveuser&#39;];    $receiveAccount = $_POST[&#39;receiveaccount&#39;];    $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 (&#39;".$payUser."&#39;, &#39;".$receiveUser."&#39;, ".$payAccount.",".$receiveAccount.",&#39;".$payWay."&#39;,&#39;".$payStatus."&#39;,".$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(&#39;pay_id&#39;,$pay_id);
                }
            }
            setcookie(&#39;pay_way&#39;,$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[&#39;pay_way&#39;])){    $payWay = $_COOKIE[&#39;pay_way&#39;];
}else{    echo "Error!";
}if($payWay == "Alipay"){    echo "<script>window.open(&#39;https://auth.alipay.com/login/index.htm?goto=https%3A%2F%2Fmy.alipay.com%2Fportal%2Fi.htm&#39;)</script>";
    //$image_url = "https://www.hkelectric.com/zh/CustomerServices/PublishingImages/Alipay_Download_QR.jpg";
    //$imageData = base64_encode(file_get_contents($image_url));
    //echo &#39;<img  src="data:image/jpeg;base64,&#39;.$imageData.&#39;" alt="PHP는 쇼핑 웹사이트를 구현합니다." >&#39;;
}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 &#39;<img  src="data:image/jpeg;base64,&#39;.$imageData.&#39;" alt="PHP는 쇼핑 웹사이트를 구현합니다." >&#39;;    echo "<script>window.open(&#39;https://pay.weixin.qq.com/index.php/public/wechatpay&#39;)</script>";
}else if($payWay == "Credit"){    echo "<script>window.open(&#39;https://bank.hangseng.com/1/2/chi/e-services/personal-ebanking/hk-personal-ebanking&#39;)</script>";
}else if($payWay == "UnionPay"){    echo "<script>window.open(&#39;https://cn.unionpay.com/front.do&#39;)</script>";
}

setcookie(&#39;pay_status&#39;,true);$sql = "UPDATE payment_info SET pay_status=1 WHERE pay_id = ".$_COOKIE[&#39;pay_id&#39;].";";$result = executeSql($sql);if($result[0]){    echo "<br>";    echo "<br>";    echo "<a href=&#39;process_order.php&#39;>Click here to see order information.</a>";
}else{    echo "You have to pay first!";
}


?>

8.查看交易信息并导出报告

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[&#39;u_id&#39;];    $d_id = $_COOKIE[&#39;d_id&#39;];    $pay_id = $_COOKIE[&#39;pay_id&#39;];    $p_info = $_COOKIE[&#39;p_info&#39;];    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.",&#39;".$o_date."&#39;,".$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(&#39;o_id&#39;,$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[&#39;p_inventory&#39;];
                }
            }            //update p_inventory
            $p_inventory = $p_inventory - $p_num;            $update_sql = "UPDATE stock_info SET p_inventory = &#39;".$p_inventory."&#39; WHERE p_id = &#39;".$p_id."&#39;;";            $update_result = executeSql($update_sql);            if($update_result[0]){
                header(&#39;location:view_order.php&#39;);
            }
        }
    }        ?>
    </body>
    </html>

2)view_order.php
//查看订单信息,并给出生成报告的链接

<!DOCTYPE html>
<html>
<head>
    <title>Order Information</title>
</head>
<body>    <?php
    if($_COOKIE[&#39;pay_status&#39;]){        $o_id = $_COOKIE[&#39;o_id&#39;];        $u_id = $_COOKIE[&#39;u_id&#39;];        $tracking_num = $_COOKIE[&#39;d_id&#39;];        $pay_id = $_COOKIE[&#39;pay_id&#39;];        $total_item = $_COOKIE[&#39;total_item&#39;];        $phones_price = $_COOKIE[&#39;phones_price&#39;];        $shipment_price = $_COOKIE[&#39;shipment_price&#39;];        $total_price = $phones_price + $shipment_price;        $pay_status = $_COOKIE[&#39;pay_status&#39;];        ?>
        <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."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=&#39;eStockReport.php&#39;>Export Product Report</a>";            echo "<br>";            echo "<br>";            echo "<a href=&#39;eOrderReport.php&#39;>Export Order Report</a>";            echo "<br>";            echo "<br>";            echo "<a href=&#39;eDeliveryReport.php&#39;>Export Delivery Report</a>";

        }else{
            header(&#39;location:payInfo.php&#39;);
        }    ?>
    </body>
    </html>

9.导出报告

1)eOrderReport.php
//导出订单报告

<!DOCTYPE html>
<html>
<head>
    <title>Export Report</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);
            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);    //关闭文件句柄
    fclose($myfile);

    header(&#39;location:view_order.php&#39;);    ?></body>
</html>

2)eStockReport.php
//导出库存报告

<!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 array
            if($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);    //关闭文件句柄
    fclose($myfile);    function php_sendmail($stream){
        require(&#39;class.phpmailer.php&#39;);  

//$mail->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(&#39;xx.xls&#39;,&#39;我的附件.xls&#39;); // 添加附件,并指定名称  $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(&#39;location:view_order.php&#39;);?></body>
</html>

3)eDeliveryReport.php
//导出物流报告

<!DOCTYPE html>
<html>
<head>
    <title>Export Report</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);
            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);    //关闭文件句柄
    fclose($myfile);

    header(&#39;location:view_order.php&#39;);    ?></body>
</html>

10.搜索功能

做了一个分类搜索的功能,用的就是数据库的模糊查询,很简单
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><?php
    if(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&#39;t be empty!";            echo "<br>";
        }else{            $sql = "SELECT * FROM product_info WHERE p_brand LIKE &#39;%".$value."%&#39;;";
            showResult($sql);

        }
    }else if($selected_Condition == "name"){        $value = $_POST["value"];        if($value ==""){            echo "The value can&#39;t be empty!";            echo "<br>";
        }else{            $sql = "SELECT * FROM product_info WHERE p_name LIKE &#39;%".$value."%&#39;;";
            showResult($sql);
        }

    }else if($selected_Condition == "type"){        $value = $_POST["value"];        if($value ==""){            echo "The value can&#39;t be empty!";            echo "<br>";
        }else{            $sql = "SELECT * FROM product_info WHERE p_type LIKE &#39;%".$value."%&#39;;";
            showResult($sql);
        }

    }else if($selected_Condition == "color"){        $value = $_POST["value"];        if($value ==""){            echo "The value can&#39;t be empty!";            echo "<br>";
        }else{            $sql = "SELECT * FROM product_info WHERE p_color LIKE &#39;%".$value."%&#39;;";
            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&#39;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 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 &#39;<table border="1">&#39;;            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 &#39;<td><img  src="data:image/jpeg;base64,&#39;.$imageData.&#39;" alt="PHP는 쇼핑 웹사이트를 구현합니다." ></td>&#39;;                echo "</tr>";                $i++;
            }            echo "</table>";
        }
    }?></body>
</html>

特别说明:

1)购物车用session实现
2)其他各种用户登录状态,产品id等信息,均存储在cookie数组中
3)当某种产品卖出后,会从数据库中将该产品的库存减去订单中相应的数量。

11.数据库表设计

下面是对数据库设计的一个说明,交作业用的。

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处理的过程中,产生了相应的需要,具体处理请看代码。

다음은 구체적인 테이블 이름과 필드입니다.
PHP는 쇼핑 웹사이트를 구현합니다.
PHP는 쇼핑 웹사이트를 구현합니다.
PHP는 쇼핑 웹사이트를 구현합니다.

12. 제한 사항 및 반성

이 작은 프로젝트는 총 2주에 걸쳐 매우 빡빡한 일정으로 완료되었으며 실제 유효 시간은 단 1초였습니다. 10일 정도 됐고, 중간에 다른 프로젝트로 바빴어요. 그래서 아쉬운 점이 많습니다.
일부 코드는 더 간결하게 작성되고 병합될 수 있었습니다.
데이터베이스 연결 및 기타 SQL 문 실행 작업을 캡슐화하여 별도의 파일로 호출할 수 있으며, 사용 위치에 관계없이 처리하기도 비교적 간단합니다.
데이터베이스 연결에는 두 가지 방법이 있는데, 통일되지 않습니다.

아직 개선할 부분이 많습니다.

관련 추천:

PHP는 WeChat 웹페이지 로그인 인증 개발을 구현합니다

위 내용은 PHP는 쇼핑 웹사이트를 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:라라벨 권한 관리다음 기사:라라벨 권한 관리