当前位置 博文首页 > fareast_mzh的博客:php简单的通信录

    fareast_mzh的博客:php简单的通信录

    作者:[db:作者] 时间:2021-08-24 18:43

    ?

    * exam.sql

    CREATE DATABASE /*!32312 IF NOT EXISTS*/ `exam` /*!40100 DEFAULT CHARACTER SET utf8 */;
    
    USE `exam`;
    
    --
    -- Table structure for table `phones`
    --
    
    DROP TABLE IF EXISTS `phones`;
    /*!40101 SET @saved_cs_client     = @@character_set_client */;
    /*!40101 SET character_set_client = utf8 */;
    CREATE TABLE `phones` (
      `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'sequence id',
      `first_name` varchar(32) NOT NULL COMMENT 'fist name',
      `last_name` varchar(32) NOT NULL COMMENT 'last name',
      `zip_code` varchar(16) NOT NULL DEFAULT '000000',
      `phone_number` varchar(16) NOT NULL DEFAULT '',
      `created_at` datetime NOT NULL COMMENT 'create datetime',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='contacts';
    /*!40101 SET character_set_client = @saved_cs_client */;

    做项目一直用框架,好长时间没用过原生的PHP和原生的Javascript

    * hw7_4.php

    <?php
    
    function getSettings() {
        return [
            'host' => '127.0.0.1',
            'port' => '3306',
            'dbname' => 'exam',
            'username' => '数据库用户名',
            'password' => '数据库密码',
            'charset' => 'utf8'
        ];
    }
    
    function getDB() {
        $set = getSettings();
        $db = new mysqli($set['host'], $set['username'], $set['password'], $set['dbname'],
            $set['port']);
        if (!$db) {
            echo $db->connect_error;
            return null;
        }
        $db->set_charset($set['charset']);
        return $db;
    }
    
    /**
     * @param $a array
     */
    function xhrReturn($a) {
        echo json_encode($a);
        exit(0);
    }
    
    function createUser() {
        $firstName = $_POST['first_name'];
        $lastName = $_POST['last_name'];
        $zipCode = $_POST['zip_code'] ? $_POST['zip_code']:'000000';
        $phoneNumber = $_POST['phone_number'];
    
        if (!preg_match('/^(\+[0-9]{2,3})?1[356789][0-9]{9}$/', $phoneNumber)) {
            xhrReturn(['code'=>400, 'data'=>null,'msg'=>'Invalid phone number']);
        }
    
        $db = getDB();
        $tpl = <<<EOF
    INSERT INTO `phones`(`first_name`,`last_name`,`zip_code`,`phone_number`,`created_at`)
    VALUES('%s','%s','%s','%s','%s')
    EOF;
        $sql = sprintf($tpl, $firstName, $lastName, $zipCode, $phoneNumber, date("Y-m-d H:i:s", time()));
        $b = $db->query($sql);
        if (!$b) {
            xhrReturn(['code'=>500, 'data' => null, 'msg' => 'Insert error']);
        }
    
        header("Location: hw7_4.php");
    }
    
    function showUsers() {
        $sql = <<<EOF
    SELECT `id`,`first_name`,`last_name`,`zip_code`,`phone_number`,`created_at` FROM `phones`
    ORDER BY `id` DESC
    EOF;
        $rows = getDB()->query($sql)->fetch_all(MYSQLI_ASSOC);
        echo "<table>";
        echo "<thead><tr><th></th><th>first_name</th><th>last_name</th><th>zip_code</th><th>phone_number</th><th>created_at</th></tr></thead>";
        echo "<tbody>";
        foreach ($rows as $row) {
            echo "<tr>".
                "<td><input type='checkbox' name='ids' value='".$row['id']."' /></td>".
                "<td>".$row['first_name']."</td>".
                "<td>".$row['last_name']."</td>".
                "<td>".$row['zip_code']."</td>".
                "<td>".$row['phone_number']."</td>".
                "<td>".$row['created_at']."</td>".
                "</tr>";
        }
        echo "</tbody></table>";
    }
    
    function deleteUser() {
        $ids = explode(',', $_POST['ids']);
    
        $db = getDB();
        foreach ($ids as $id) {
            $sql = sprintf("DELETE FROM `phones` WHERE `id`='%d'", $id);
            $db->query($sql);
        }
        header("Location: hw7_4.php");
    }
    
    ?>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>hw7_4 Contacts</title>
        <style>
            #mask {
                width: 100%;
                z-index: 2;
                opacity: .2;
                height: 100%;
                position: absolute;
                left: 0;
                top: 0;
                background-color: #2b2b2b;
                display: none;
            }
            .modal {
                display: none;
                border: 1px solid #ccc;
                padding: 10px;
                z-index: 3;
            }
            .modal.show {
                display: block;
                width: 170px;
                z-index: 4;
                background-color: #fff;
                position: absolute;
                top: 50px;
                left: 20px;
            }
            .container {margin: 20px 10px;}
            .form-group {margin-bottom: 10px; }
            .modal-title {margin: 0 auto 10px; text-align: center;}
            .btnWrap .btn-submit {margin: 0 auto;display: block;}
            table {margin-top: 20px; border:1px solid #ccc;}
            thead th {background-color: #cecece;}
            .btnWrap .btn-danger {margin-left: 4em;}
            tbody tr:nth-child(2n) {background-color: #efefef;}
            tbody tr:nth-child(2n+1) {background-color: #ffffff;}
    
        </style>
    </head>
    <body>
    
    <div class="container">
        <div class="btnWrap">
            <button onclick="popupNew()">New contacts</button>
            <button class="btn-danger" onclick="delEntry()">Delete contacts</button>
        </div>
    
    <?php
    // dispatch actions
    $action = isset($_GET['action']) ? $_GET['action']: 'index';
    
    if ($action==="new") {
        if ($_POST) {
            createUser();
        } else {
            echo "ERROR: Unexpected POST request";
            exit(402);
        }
    
    } else if ($action==="delete") {
        deleteUser();
    } else {
        showUsers();
    }
        ?>
    
    </div>
    
    <div id="mask"></div>
    <div id="modal_1" class="modal">
        <div class="modal-title">New contacts</div>
        <div class="modal-body">
            <form method="POST" action="hw7_4.php?action=new">
                <div class="form-group">
                    <input type="text" name="first_name" required placeholder="first name" value="" />
                </div>
                <div class="form-group">
                    <input type="text" name="last_name" required placeholder="last name" value="" />
                </div>
                <div class="form-group">
                    <input type="text" name="zip_code" placeholder="zip code" value="" />
                </div>
                <div class="form-group">
                    <input type="text" name="phone_number" required placeholder="phone_number" value="" />
                </div>
                <div class="btnWrap">
                    <button class="btn-submit" type="submit">Submit</button>
                </div>
    
            </form>
        </div>
    </div>
    
    <script>
        function popupNew() {
            var modal_1 = document.getElementById("modal_1");
            if ( ! modal_1.classList.contains("show")) {
                modal_1.classList.add("show");
            }
            var mask = document.getElementById("mask");
            mask.style.display = "block";
            mask.onclick = hidePopup;
        }
    
        function hidePopup(e) {
            var modal_1 = document.getElementById("modal_1");
            if ( modal_1.classList.contains("show")) {
                modal_1.classList.remove("show");
            }
            var mask = document.getElementById("mask");
            mask.style.display = "none";
            mask.removeEventListener("click", "hidePopup")
        }
    
        function delEntry() {
            var form = document.createElement("form");
            form.style.display = "none";
            form.method = "POST";
            form.action = "hw7_4.php?action=delete";
    
            var input = document.createElement("input");
            input.name = "ids";
    
            var a = Array.prototype.map.call(document.getElementsByName("ids"), function(c) {
                if (c.checked) {
                    return c.value;
                }
                return 0;
            }).filter(function(el) {
                return el !== 0;
            });
    
            console.log(a);
            if (a.length < 1) {
                alert("At least pick one entry");
                return;
            }
            var ans = confirm("Are you sure to delete these entries?");
            if (!ans) {
                return;
            }
    
            input.value = a.join(',');
            form.appendChild(input);
    
            document.body.appendChild(form);
            form.submit();
        }
    </script>
    
    </body>
    </html>
    

    这是一个考试题,时间有限,这样简单的界面应该可以了。

    ?

    ?

    ?

    ?

    cs
    下一篇:没有了