zoukankan      html  css  js  c++  java
  • WEB前端第五十九课——时间戳、数据交互小案例

    1.时间戳

      程序开发中所说的时间戳,通常是指从1970年1月1日0时到当前时间的毫秒数。

      time()方法,用于获取当前的时间戳,结果为毫秒数。

      date()方法,用于将时间戳结果转换为通常的时间格式。

      语法:date(format,timeStamp);  //format参数用于定义日期时间格式

      时间格式:

        年:Y 4位数年份    y 2位数年份

        月:M 3位英文简写     F 完整英文月份    m 2位数月份  n 无0数字月份

        日:d 2位数月第几天  j 无0补位月第几天 S  月第几天英序数后缀  z 年第几天

        星期:D 3为英文简写  l 完整英文星期几(小写L)

        时:H 24小时制  G 无0 24小时制  h 12小时制  g 无0 12小时制

          A(AM/PM)  a(am/pm)

        分:i 2位数分钟

        秒:s 2位数秒钟

        时区:e 时区标识符  T 时区简写

      注意:年月日与时间之间通常使用“空格”隔开,

         年月日之间的连接符通常使用“-或/”,英文日期多用“空格与of”拼接,时间之间的连接符通常使用“:”。

      代码示例:

    <?php
        echo time();
        echo '<br>';
        echo date('Y-m-d H:i:s',time());
        echo '<br>';
        echo date('D jS of F Y h:i:s a');   //可不写 time()方法。
        echo '<br>';
    //    设置默认时区
        date_default_timezone_set('Asia/Shanghai');
        echo date('Y-m-d H:i:s',time());
    ?>
    

    2.fetch相关方法

      ⑴ fetchAll($result,resulttype),从结果中获取所有行数据作为关联数组。

        参数result为必需,是由mysqli_query()、mysqli_store_result() 或 mysqli_use_result() 返回的结果,

        也可以通过result结果集标识符通过指针调用 fetchAll() 方法。

        参数resulttype为可选,用于规定输出那种类型的数组。包括“_ASSOC、_NUM\_BOTH”三种。

      ⑵ fetch_assoc($result),从结果集中获取一行数据作为关联数组。

      ⑶ fetch_row($result),从结果集中获取一行数据作为枚举数组。

      ⑷ fetch_column($result),从结果集中获取一列数据作为枚举数组。

      注意:在PHP PDO中有很多关于 fetch 的预定义常量,可以通过 PDO调用。

    3.前后台交互案例

      新增、删除、修改、文章详情小案例

      数据库表结构:

      

       ⑴ index.php页面

        注意链接数据库时,使用 try{}catch(){} 固定格式,便于连接异常问题分析;

        首页界面设计包括 页面布局和数据库取数逻辑,HTML代码和PHP代码穿插结合使用;

        在HTML中引用PHP代码时,需要使用<?php ?>标识包裹;

        在PHP中引用HTML代码时,需要使用<script></script>标签包裹;

        使用 table 列表展示文章列表,PHP获取数据库数据时,通过字符串拼接的方式生成<tr><td>行。

    <?php
        try{
            $con = new PDO("mysql:host=localhost;dbname=dbTest","root","");
            $con->exec('set names utf8');       //也可以在上述PDO()方法的第一个参数中添加“charset=utf8”
            $con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
            $sql = "select * from news where 1";
            $res = $con->query($sql);
            $resInfo = $res->fetchAll(PDO::FETCH_ASSOC);
    //        print_r($resInfo);
            $newsInfo = "";
            if($res){
                for($i=0;$i<count($resInfo);$i++){
    //            通过字符串“.”点号拼接的方式获取“$resInfo”数组中的信息,获取字段数据使用“{}”包裹变量。
                    $newsInfo.="<tr>
                        <td>{$resInfo[$i]['id']}</td><td>{$resInfo[$i]['title']}</td>
                        <td>{$resInfo[$i]['author']}</td><td>{$resInfo[$i]['summary']}</td>
                        <td>{$resInfo[$i]['time']}</td>
                        <td>
                            <a href='updNews.php?id={$resInfo[$i]['id']}'>修改</a>
                            <a href='delNews.php?id={$resInfo[$i]['id']}'>删除</a>
                            <a href='detailNews.php?id={$resInfo[$i]['id']}'>详情</a>
                        </td>
                    </tr>";
                }
            }else{
                echo '<script>alert("数据为空")</script>';
            }                             
        }catch(PDOException $e){
            echo '数据库连接失败!错误信息:'.$e->getMessage();
        }
    ?>
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>秋香news</title>
        <link rel="stylesheet" href="./JSFiles/bootstrap.min.css">
        <script src="./JSFiles/jquery-1.12.4.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.min.js"></script>
    
        <style>
            .container{
                margin:20px auto;
            }
            th{
                text-align: center;
                vertical-align: middle!important;   //此处样式需要使用“!important”强制优先,样式才会生效!
            }
    
            .leftCon{
                border-left: 1px solid hotpink;
            }
            .leftCon a{
                display: block;
                margin: 10px 0;
                padding: 2px 0;
                color: darkorange;
                border-bottom: 1px solid pink;
                text-decoration: none;
            }
        </style>
    </head>
    <body>
    <div class="container" >
        <div class="row" >
            <div class="col-2 leftCon">
                <a href='#'>文档列表</a>
                <a href='create.html'>添加文章</a>
            </div>
            <div class="col-10">
                <table class="table table-sm table-hover table-bordered">
                    <thead class="thead-dark">
                    <tr>
                        <th scope="col">ID</th>
                        <th scope="col">标题</th>
                        <th scope="col">作者</th>
                        <th scope="col">文章概要</th>
                        <th scope="col">时间</th>
                        <th scope="col">操作</th>
                    </tr>
                    </thead>
                    <tbody class="thead-light">
                        <?php
                            echo $newsInfo;
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    </body>
    </html>
    

      ⑵ create.html 新增文章页面

        使用 form 表单形式创建界面,表单提交的字段 name 须与后台接收字段名一致!

        BootStrap 组件中,label标签的 for 属性值与input标签的 id 属性值必须保持一致!

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>新增文章</title>
        <link rel="stylesheet" href="./JSFiles/bootstrap.min.css">
        <script src="./JSFiles/jquery-1.12.4.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.min.js"></script>
    
        <style>
            .container{
                margin:20px auto;
            }
            .btn{
                display: block;
                margin: 0 auto;
            }
    
            .leftCon{
                border-left: 1px solid hotpink;
            }
            .leftCon a{
                display: block;
                margin: 5px 0;
                padding: 2px 0;
                color: darkorange;
                border-bottom: 1px solid pink;
                text-decoration: none;
            }
        </style>
    </head>
    <body>
    <div class="container" >
        <div class="row" >
            <div class="col-2 leftCon">
                <a href='#'>创建文章</a>
            </div>
            <div class="col-10 rightCon">
    <!--        form表单提交目标地址使用 action 属性定义    -->
                <form action="submit.php" method="post">
                    <div class="form-group row">
                        <label for="inputTitle" class="col-sm-1 col-form-label-lg">标题</label>
                        <div class="col-sm-11">
                            <input type="text" class="form-control" id="inputTitle" name="inputTitle">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="inputAuthor" class="col-sm-1 col-form-label-lg">作者</label>
                        <div class="col-sm-11">
                            <input type="text" class="form-control" id="inputAuthor" name="inputAuthor">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="inputSummary" class="col-sm-1 col-form-label-lg">概要</label>
                        <div class="col-sm-11">
                            <input type="text" class="form-control" id="inputSummary" name="inputSummary">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="inputContent" class="col-sm-1 col-form-label-lg">内容</label>
                        <div class="col-sm-11">
                            <textarea type="text" class="form-control" id="inputContent" rows="15" name="inputContent"></textarea>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-success">Submit</button>
                </form>
            </div>
        </div>
    </div>
    </body>
    </html>
    

      ⑶ submit.php提交数据页面

        可使用“$_GET”或“$_POST”方法接收前台页面发送的数据,方法在 form method属性中定义;

        接收数据时可以使用 三目运算 判断字段值是否为空的情况;

        操作时间直接使用 time() 方法生成系统时间,不需要接收;

        注意设置默认时区,方法:date_default_timezone_set('Asia/Shanghai');

        调用字段值时,使用“{}”包裹变量;

        使用“echo()”方法向前台返回数据,返回内容可以是 <script>代码。

    <?php
        //接收前台页面提交的信息,可通过三目运算判断值是否为空。
        $id=isset($_POST['inputId'])?$_POST['inputId']:'';
        $title=isset($_POST['inputTitle'])?$_POST['inputTitle']:'';
        $author=isset($_POST['inputAuthor'])?$_POST['inputAuthor']:'';
        $summary=isset($_POST['inputSummary'])?$_POST['inputSummary']:'';
        $content=isset($_POST['inputContent'])?$_POST['inputContent']:'';
        date_default_timezone_set('Asia/Shanghai');
        $time=date('Y-m-d H:i:s',time());
        try{
            $con=new PDO('mysql:host=localhost;dbname=dbTest;charset=utf8','root','');
            $con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    //        接收信息写入数据库,SQL接收数据字段时使用 {} 提取!!!
            if($id==''){
                $sql="insert into news(title,author,summary,content,time) values('{$title}','{$author}','{$summary}','{$content}','{$time}')";
                $res=$con->query($sql);
                if($res){
        //        返回操作信息,可以直接在PHP中返回js语句给前台
                    echo '<script>alert("创建成功!");window.location.href="index.php"</script>';
                }else{
                    echo "创建失败!";
                }
            }else{
                $sql="update news set title='{$title}',author='{$author}',summary='{$summary}',content='{$content}',time='{$time}' where id='{$id}'";
                $res=$con->query($sql);
                if($res){
        //        返回操作信息,可以直接在PHP中返回js语句给前台
                    echo '<script>alert("修改成功!");window.location.href="index.php"</script>';
                }else{
                    echo "修改失败!";
                }
            }
        }catch(PDOException $e){
            echo "数据库连接失败!错误信息:".$e->getMessage();
        }
    ?>
    

      ⑷ delnews.php 删除数据

        删除、修改、详情操作均通过在前台定义<a>标签的方式,发送操作指令;

        在<a>标签中设置href链接地址,url后接“?”将当前操作id发送至后台;

        后台使用“$_GET”方法接收id值,判断删除对应的数据行。

    <?php
        $id=isset($_GET['id'])?$_GET['id']:'';
        if($id){
            try{
                $con=new PDO('mysql:host=localhost;dbname=dbTest;charset=utf8','root','');
                $con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        //        接收信息写入数据库,SQL接收数据字段时使用 {} 提取
                $sql="delete from news where id={$id}";
                $res=$con->query($sql);
                if($res){
        //        返回操作信息,可以直接在PHP中返回js语句给前台
                    echo '<script>alert("删除成功!");window.location.href="index.php"</script>';
                }else{
                    echo "删除失败!";
                }
            }catch(PDOException $e){
                echo "数据库连接失败!错误信息:".$e->getMessage();
            }
        }else{
            echo "删除数据ID不存在!";
        }
    ?>
    

      ⑸ updnews.php 修改数据

        获取操作数据行id后查询数据库,同新增数据页面样式展示目标数据;

        在 input value属性中设置 PHP 输出代码,将查询数据展示到界面;

        提交数据可以与新增提交共用后台逻辑,使用if判断新增还是修改。

    <?php
        $id=isset($_GET['id'])?$_GET['id']:'';
        if($id){
            try{
                $con=new PDO('mysql:host=localhost;dbname=dbTest;charset=utf8','root','');
                $con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        //        接收ID值,通过id查询该条数据,使用 {} 获取id。
                $sql = "select * from news where id={$id}";
                $res = $con->query($sql);
                $resInfo = $res->fetchAll(PDO::FETCH_ASSOC);
    //            print_r($resInfo);
            }catch(PDOException $e){
                echo "数据库连接失败!错误信息:".$e->getMessage();
            }
        }else{
            echo "数据查询失败!";
        }
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>新增文章</title>
        <link rel="stylesheet" href="./JSFiles/bootstrap.min.css">
        <script src="./JSFiles/jquery-1.12.4.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.min.js"></script>
    
        <style>
            .container{
                margin:20px auto;
            }
            .btn{
                display: block;
                margin: 0 auto;
            }
    
            .leftCon{
                border-left: 1px solid hotpink;
            }
            .leftCon a{
                display: block;
                margin: 5px 0;
                padding: 2px 0;
                color: darkorange;
                border-bottom: 1px solid pink;
                text-decoration: none;
            }
        </style>
    </head>
    <body>
    <div class="container" >
        <div class="row" >
            <div class="col-2 leftCon">
                <a href='#'>修改文章</a>
            </div>
            <div class="col-10 rightCon">
    <!--        form表单提交目标地址使用 action 属性定义    -->
                <form action="update.php" method="post">
    <!--            添加 id 字段用于提交后台时根据 id条件判断修改哪一条数据,display隐藏显示。   -->
                    <input type="number" style="display:none" name="inputId" value="<?php echo $resInfo[0]['id'] ?>">
                    <div class="form-group row">
                        <label for="inputTitle" class="col-sm-1 col-form-label-lg">标题</label>
                        <div class="col-sm-11">
    <!--                    注意:通过<input>标签的 value 属性进行赋值,赋值时必须使用 PHP echo 格式输出!!    -->
                            <input type="text" class="form-control" id="inputTitle" name="inputTitle" value="<?php echo $resInfo[0]['title'] ?>">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="inputAuthor" class="col-sm-1 col-form-label-lg">作者</label>
                        <div class="col-sm-11">
                            <input type="text" class="form-control" id="inputAuthor" name="inputAuthor" value="<?php echo $resInfo[0]['author'] ?>">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="inputSummary" class="col-sm-1 col-form-label-lg">概要</label>
                        <div class="col-sm-11">
                            <input type="text" class="form-control" id="inputSummary" name="inputSummary" value="<?php echo $resInfo[0]['summary'] ?>">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="inputContent" class="col-sm-1 col-form-label-lg">内容</label>
                        <div class="col-sm-11">
    <!--                    注意:<textarea>未块级元素,直接在标签内部赋值!!  -->
                            <textarea type="text" class="form-control" id="inputContent" rows="15" name="inputContent"><?php echo $resInfo[0]['content'] ?></textarea>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-success">Submit</button>
                </form>
            </div>
        </div>
    </div>
    </body>
    </html>
    

      ⑹ update.php 提交修改数据

    <?php
        $id=isset($_POST['inputId'])?$_POST['inputId']:'';
        if($id){
            $title=isset($_POST['inputTitle'])?$_POST['inputTitle']:'';
            $author=isset($_POST['inputAuthor'])?$_POST['inputAuthor']:'';
            $summary=isset($_POST['inputSummary'])?$_POST['inputSummary']:'';
            $content=isset($_POST['inputContent'])?$_POST['inputContent']:'';
            date_default_timezone_set('Asia/Shanghai');
            $time=date('Y-m-d H:i:s',time());
            try{
                $con=new PDO("mysql:host=localhost;dbname=dbTest;charset=utf8","root","");
                $con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
                $sql="update news set title='{$title}',author='{$author}',summary='{$summary}',content='{$content}',time='{$time}' where id='{$id}'";
                $res=$con->query($sql);
                if($res){
                    echo '<script>alert("修改成功!");window.location.href="index.php"</script>';
                }else{
                    echo "<script>alert('修改失败!');window.location.href='index.php'</script>";
                }
            }catch(PDOException $err){
                echo "当前数据id不存在!".$err->getMessage();
            }
        }
    ?>
    

      ⑺ detailnews.php 查询详情

        在PHP中通过id查询操作数据,然后在HTML中展示结果;

        HTML中展示查询结果时,使用PHP代码获取数据。

    <?php
        $id=isset($_GET['id'])?$_GET['id']:'';
        if($id){
            try{
                $con = new PDO("mysql:host=localhost;dbname=dbTest","root","");
                $con->exec('set names utf8');       //也可以在上述PDO()方法的第一个参数中添加“charset=utf8”
                $con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
                $sql = "select * from news where id='{$id}'";
                $res = $con->query($sql);
                $resInfo = $res->fetchAll(PDO::FETCH_ASSOC);
    //            print_r($resInfo);
            }catch(PDOException $e){
                echo '数据库连接失败!错误信息:'.$e->getMessage();
            }
        }
    ?>
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>news正文</title>
        <link rel="stylesheet" href="./JSFiles/bootstrap.min.css">
        <script src="./JSFiles/jquery-1.12.4.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.min.js"></script>
    
        <style>
            .container{
                margin:20px auto;
            }
            h3{
                height: 50px;
            }
            small{
                height: 20px;
            }
            .leftSpan{
                left:0;
            }
            .rightSpan{
                display:block;
                right:0;
                float:right;
            }
        </style>
    </head>
    <body>
    <div class="container" >
        <div class="row" >
            <div class="col">
                <h3><?php echo $resInfo[0]['title'] ?></h3>
                <small>
                    <span class="leftSpan"><?php echo $resInfo[0]['author']?></span>
                    <span class="rightSpan"><?php echo $resInfo[0]['time'] ?></span>
                </small>
                <p style="margin:10px auto;padding:20px 0 10px;border-top:1px solid pink">
                    <?php echo $resInfo[0]['summary'] ?>
                </p>
                <p><?php echo $resInfo[0]['content'] ?></p>
            <div>
    
        </div>
    <!--         -->
    </div>
    </body>
    </html>
    

      

  • 相关阅读:
    进程状态-top,ps
    怎么杀死进程?
    linux文件属性和类型
    文件管理的相关命令
    系统的目录结构
    linux基础_02
    linux基础_01
    python 01
    什么是NoSql
    为何不推荐子查询和join?
  • 原文地址:https://www.cnblogs.com/husa/p/14273070.html
Copyright © 2011-2022 走看看