zoukankan      html  css  js  c++  java
  • 前端小白之每天学习记录----php(9)简单的api

    首先了解跨表语句where( inner JOIN ),LEFT JOIN(左关联),RIGHT JOIN(右关联)

    假设有两张表

    表1:

    category

    cat_id    cat_name          parent_id
    1            web开发               0
    2             js                         1
    3             php                      1
    4             java                      1
    5             安卓开发              0
    6              es6                      2

    表2:
    article

    arc_id     title      content      cat_id
    1            xx1            xx1            2
    2            xx2            xx2            3

    where( inner JOIN ):
    两者同时满足: 两边的表数据 要同时匹配

    SELECT * FROM article AS arc, category AS c WHERE arc.`cat_id` = c.`cat_id`
    SELECT * FROM article AS arc INNER JOIN category c ON arc.`cat_id` = c.`cat_id`;

    LEFT JOIN(左关联)
    SELECT 字段名 FROM 左表 LEFT JOIN 右表 ON 左表.字段 = 右表.字段
    以左表为基准, 哪怕左表中的记录/字段, 在右表中没有对应的数据,依然会把所有的左表数据
    查询输出
    RIGHT JOIN(右关联)
    SELECT 字段名 FROM 左表 RIGHT JOIN 右表 ON 左表.字段 = 右表.字段
    以右表为基准, 哪怕右表中的记录/字段, 在左表中没有对应的数据,依然会把所有的右表数据
    查询输出

    后台封装api,前端用ajax取数据

    例子:

    实现的功能:取出小说分类

    需要的页面:

    1.测试用表格

    2.封装的数据库curd操作的页面(Mysql.class.php)

    3.封装的分类小说表格curd操作页面(Category.class.php)

    4.封装的api页面(category.php)

    5.ajax调用html测试页面(index.php)

    1.测试用表格(在数据库php_cs1)新建category表:

      cat_id       cat_name

      1     玄幻小说

      2     奇幻小说

      3     都市小说

      4     科幻小说

      5     言情小说

    2.封装的数据库curd操作的页面(Mysql.class.php)

    <?php
        class Mysql {
            private $host; //主机名
            private $dbName; //数据库名称
            private $userName; //用户名
            private $userPWd; //密码
    
            public function __construct( $_host, $_dbName, $_userName, $_userPwd ){
                $this->host = $_host;
                $this->dbName = $_dbName;
                $this->userName = $_userName;
                $this->userPwd = $_userPwd;
                if( !$this->connect() ){
                    die( mysql_error() );
                }
                //设置编码
                $this->setCode();
                //选择数据库
                $this->selectDb();
            }
    
            public function connect(){
                return mysql_connect( $this->host, $this->userName, $this->userPwd );
            }
    
            public function setCode(){
                $this->query( "set names utf8" );
            }
            
            public function selectDb(){
                mysql_select_db( $this->dbName );
            }
    
            public function query( $sql ){
                return mysql_query( $sql );
            }
    
            //用来查询所有的数据
            public function getAll( $sql ){
                $res = $this->query( $sql );
                $list = array();
                while( $row = mysql_fetch_assoc( $res ) ){
                    // array_push( $list, $row );
                    $list[] = $row;
                }
                return $list;
            }
    
            //查询一行数据
            public function getRow( $sql ){
                $res = $this->query( $sql );
                return mysql_fetch_assoc( $res );
            }
    
            //查询某一列
            public function getCol( $sql ){
                $res = $this->query( $sql );
                $row = mysql_fetch_row( $res );
                return $row[0];
            }
    
            //插入
            public function add( $data, $tbName ){
                $sql = "INSERT INTO {$tbName}("; //insert into message (
                $sql .= implode( ',', array_keys( $data ) ) . " ) VALUES ( '";
                $sql .= implode( "','", array_values( $data ) ) . "')";
                // echo $sql;
                return $this->query( $sql );
            }
    
            // UPDATE message SET title = 'hello', content = '你好' WHERE msg_id = 1
            public function update( $data, $tbName, $condition ){
                $sql = "UPDATE {$tbName} SET ";
                foreach( $data as $k => $v ){
                    $sql .= $k . ' = ' . "'$v',";
                }
                // UPDATE message SET title = 'hello', content = '你好',
                $sql = substr( $sql, 0, -1 ); 
                $sql .= " " . $condition;
                return $this->query( $sql );
            }
    
    
        }
    
    
        $mysql = new Mysql( "localhost", "php_cs1", "root", "root" );
        // $mysql->add() $mysql->update()  $mysql->delete()...
    ?>
    

    3.封装的分类小说表格curd操作页面(Category.class.php) 

    <?php
        // require( "./Mysql.class.php" );
    
        class Category {
            //类中的属性叫成员变量
            //类中的方法叫成员方法
            private $tbName = 'category'; //表名
            private $objLink = null;
    
            public function __construct( $dbLink ){
                $this->objLink = $dbLink;
            }
    
            public function getCategory( $catId ){ //根据分类id查询信息
                //$catId 没传参或=0时查讯所有小说分类
                if( empty( $catId ) )
                    return $this->objLink->getAll( "SELECT * FROM {$this->tbName}" );
                else 
                    return $this->objLink->getRow( "SELECT * FROM {$this->tbName} WHERE cat_id = {$catId}" );
            }
    
            public function addCategory( $data ){ //增加信息
                if( $this->hasCategory( $data['cat_name'] ) ){
                    return false;
                }else {
                    return $this->objLink->add( $data, $this->tbName );
                }
            }
    
            public function hasCategory( $catName ){ //查询是否有分类名
                $sql = "SELECT * FROM {$this->tbName} WHERE cat_name = '$catName'";
                $res = $this->objLink->query( $sql );
                return ( $res && mysql_num_rows( $res ) );
            }
        }
    
        // $cat = new Category( $mysql );
        // $catList = $cat->getCategory( 0 );
        // $catList = $cat->getCategory( 1 );
        // print_r( $catList );
        // if( $cat->addCategory( array(
        //     'cat_name' => '言情小说',
        // ) ) ){
        //     echo 'ok';
        // }else {
        //     echo 'error';
        // }
    ?>
    

    4.封装的api页面(category.php) 

    <?php
        require( "./lib/Mysql.class.php" );//封装了数据库连接 数据的curd操作
        require( "./lib/Category.class.php" );//封装了针对Category表的操作
    
        $cat = new Category( $mysql );
    
        $act = isset( $_REQUEST['act'] ) ? $_REQUEST['act'] : 'getAll';  //api:接收到的指令
        $list = array();
    
        switch( $act ){  //根据接收到的指令执行的动作
            case 'getAll': //获取所有的分类
                $list = $cat->getCategory( 0 );
                echo json_encode( $list );//返回数据
                break;
            case 'add':
                //添加分类
                break;
        }
    
    ?>
    

    5.ajax调用html测试页面(index.php)

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
      <script src="https://cdn.bootcss.com/jquery/1.8.2/jquery.min.js"></script>
      <script>
          $(function(){
              $.get("category.php", {act:'getAll'}, function( res ){  //ajax get 方法提交信息给api
                  var oUl = document.querySelector("header > nav > ul");
                  var obj = JSON.parse( res );    //处理返回的数据
                  var html = '';
                  for( var key in obj ){ //把数据遍历到li里面
                    html += "<li><a href='javascript:#'>" + obj[key]['cat_name'] + "</a></li>";
                  }
                  oUl.innerHTML = html;
              } );
          });
      </script>
    </head>
    
    <body>
      <header>
          <nav>
              <ul>
              </ul>
          </nav>
      </header>
    </body>
    
    </html>
    

      

  • 相关阅读:
    Codeforces Round #436 C. Bus
    Codeforces Round #436 B. Polycarp and Letters
    Codeforces Round #436 A. Fair Game
    Codeforces Round #439 C. The Intriguing Obsession
    Codeforces Round #438 C. Qualification Rounds
    Codeforces Round #438 B. Race Against Time
    hdu 1394 Minimum Inversion Number (树状数组求逆序对)
    hdu 6318 Swaps and Inversions (线段树求逆序对数)
    ACM/ICPC 2018亚洲区预选赛北京赛站网络赛 D 80 Days (线段树查询最小值)
    hdu 6299 Balanced Sequence (贪心)
  • 原文地址:https://www.cnblogs.com/szlxb/p/7396282.html
Copyright © 2011-2022 走看看