Summary of TP Coherent Operation of True XX Project

Keywords: SQL Database REST less

Summary of TP Coherent Operation of True XX Project

Usage of field method

Reference link: CURD method inventory: field method

Used for query

  • field method is the most frequently used method in query operations.

    eg1: $Model
        ->field('id,title,content')
        ->select();
    

    The replication code here uses the field method to specify the values of the three fields of id, title and content in the result set of the query. The execution of SQL is equivalent to:
    SELECT id,title,content FROM table

  • Alias can be used as

    eg2: $Select
            ->field('id as role_id,role_name,role_type')
            ->select();
    
  • The definition of array mode can define aliases for certain fields

    eg: $Model
            ->field(array('id','title'=>'name','content'))
            ->select();
    
  • Queries with while() and find()

    M('User')
        ->where('id='.$userid)
        ->field('id as userid,user_role,follow,fans,love,head as photo,city,nickname,sex,age,message')
        ->find();
    

ps: while provides a query condition, find only queries one, that is, the system automatically adds LIMIT 1 restrictions

find Reference Link: ThinkPHP find method queries a data record

  • Table Alias Paging Query

    $Follow
        ->alias('c')   
            //Give the watch an alias. Alias is used to set aliases for the current data table
            //It is easy to use other coherent operations such as join method.
        ->join('__USER__ u ON c.c_bei= u.id')
            //The JOIN method is the only method that can be called multiple times in a coherent operation.
        ->where("c.c_zhu='{$userid}'")
        ->field('c.c_bei,u.id as accountid,u.sex,u.nickname,u.head as photo,u.message')
        ->limit($page,$number)
            //Paging query
        ->select();
            //Returns the query result of a two-dimensional array
    
  • table multitable operation

    $Model
        ->table('zca_blacklist bl,zca_user user')
            //Multi-table queries and aliases
        ->where("bl.user='{$userid}' AND bl.blacklister = user.id")
        ->field('user.id,user.nickname,user.head as photo,user.sex,user.message')
        ->limit($page,$number)
        ->select();
    

    ps:CURD method inventory: table method

  • sort

    $Photo
        ->field('url')
        ->where("album='{$albumid}'")
        ->order('add_time asc')
        ->find()['url'];
    

    ps:order method

Used for writing

  • In addition to query operations, the field method also has a very important security function - field validity detection (note: version 3.1 of this function can only be supported at the beginning). Field method combined with create method can complete the field validity detection of form submission:

    $Model
        ->field('title,email,content')
        ->create();
            // The only valid fields in the form are the title,email, and content fields.
              No matter how the user changes or adds the browser's submission fields
              Will be shielded directly
    

ps:create method

Usage of where method

Reference link: CURD Method Inventory: where Method

String condition

  • Direct queries and operations using string conditions

    $User
        ->where('type=1 AND status=1')
        ->select(); 
    

    The final generated SQL statement is: SELECT * FROM think_user WHERE type=1 AND status=1

  • If you use version 3.1 or more, when using string conditions, it is recommended to cooperate with the pretreatment mechanism to ensure more security.

    $Model
        ->where("id=%d and username='%s' andxx='%f'",array($id,$username,$xx))
        ->select();
    

    Or use:

        $Model
            ->where("id=%d and username='%s' and xx='%f'",$id,$username,$xx)
            ->select();
    

    ps: If the $id variable comes from the user's submission or URL address, if the incoming non-numeric type is non-numeric, the query operation will be forced to format it into digital format.
    The type of string preprocessing format supports specified numbers, strings, etc. Specifically, you can refer to the parameter description of vsprintf method.

    Reference link: PHP vsprintf() function


Array condition

  • General query

    $User = M("User");
         // Instantiate User Objects
    $map['name'] = 'thinkphp';
    $map['status'] = 1;
        // Pass the query condition into the query method
    $User->where($map)->select(); 
    

    Final generation: SELECT * FROM think_user WHERE name ='thinkphp'AND status=1

  • Expression Query

    $map['Field 1']  = array('Expression','Query condition 1');
    $map['Field 2']  = array('Expression','Query condition 2');
    $Model->where($map)->select(); 
    

    Expressions are case-insensitive. The query expressions supported have the following meanings:

    Expression Meaning
    EQ Equivalent to (=)
    NEQ Not equal to (<>)
    GT Greater than (>)
    EGT Greater than or equal to (>=)
    LT Less than (<)
    ELT Less than or equal to (<=)
    LIKE Fuzzy query
    [NOT] BETWEEN (not) interval query
    [NOT] IN IN
    EXP Expressions query, support SQL grammar

Examples are as follows:

  • EQ: equal to (=)

            $map['id']  = array('eq',100);
    

    Equivalent to the following query

            $map['id']  = 100;
    

    The query condition represented is id = 100

  • NEQ: Not equal to (<>)

    $map['id']  = array('neq',100);
    

    The query condition represented is ID <> 100

  • gt: greater than (>)

    $map['id']  = array('gt',100);
    

    The query condition represented is ID > 100

  • EGT: greater than or equal to (>=)

    $map['id']  = array('egt',100);
    

    The query condition represented is ID >= 100

  • lt: less than (<)

    $map['id']  = array('lt',100);
    

    The query condition represented is ID < 100

  • ELT: Less than or equal to (<=)

    $map['id']  = array('elt',100);
    

    The query condition represented is ID <= 100

  • [NOT] LIKE: LIKE with sql

    $map['name'] = array('like','thinkphp%');
    

    The query condition becomes name like'thinkphp%'
    If the DB_LIKE_FIELDS parameter is configured, some fields will be automatically fuzzed.
    For example, set up:

        'DB_LIKE_FIELDS'=>'title|content'
    

    If so, use

    $map['title'] = 'thinkphp';
    

    The query condition becomes name like'% thinkphp%'

    Support array mode, such as

    $map['a'] =array('like',array('%thinkphp%','%tp'),'OR');
    $map['b'] =array('notlike',array('%thinkphp%','%tp'),'AND');
    
    //The generated query condition is:
    (a like '%thinkphp%' OR a like '%tp') AND (b not like '%thinkphp%' AND b not like '%tp')
    
  • [NOT] BETWEEN: With sql's [not] between, query conditions support strings or arrays

    For example:

    $map['id']  = array('between','1,8');
    

    Equivalent to the following:

        $map['id']  = array('between',array('1','8'));
    

    The query condition becomes id BETWEEN 1 AND 8

  • [NOT] IN: With sql's [not] in, query conditions support strings or arrays
    For example:

    $map['id']  = array('not in','1,5,8');
    

    Equivalent to the following:

    $map['id']  = array('not in',array('1','5','8'));
    

    The query condition becomes id NOT IN (1,5, 8)

  • EXP: Expressions to support more complex queries
    For example:

    $map['id']  = array('in','1,3,8');
    

    It can be changed to the following: ___________

    $map['id']  = array('exp',' IN (1,3,8) ');
    

    exp query conditions are not treated as strings, so the following query conditions can use any SQL-supported syntax, including the use of function and field names.

    Query expressions can be used not only for query conditions, but also for data updates.

    For example:

    $User = M("User"); // Instantiate User Objects
        // Attribute assignment of data object to be modified
    $data['name'] = 'ThinkPHP';
    $data['score'] = array('exp','score+1');
        // User's integral plus 1
    
    $User
        ->where('id=5')
        ->save($data);
         // Save modified data according to conditions
    


Quick inquiry

    $User = M("User"); // Instantiate User Objects
    $map['name|title'] = 'thinkphp';
        // Pass the query condition into the query method
    $User
        ->where($map)
        ->select(); 

The query condition becomes

    name= 'thinkphp' OR title = 'thinkphp


User=M("User"); // instantiate the User object map ['status & title'] = array('1','thinkphp','_multi'=> true);
// Pass the query condition into the query method
User−>where(map)
->select();

'_multi'=> true must be added to the end of the array to indicate that the current multi-condition matching, so that the query condition becomes status= 1 AND title='thinkphp', and the query field supports more.

For example:

$map['status&score&title'] =array('1',array('gt','0'),'thinkphp','_multi'=>true);

The query condition becomes

 status= 1 AND score >0 AND title = 'thinkphp'

Note: The'|'and'&' in the shortcut query cannot be used at the same time.


Interval query

where method supports interval queries for a field.

For example:

  • AND

    $map['id'] = array(array('gt',1),array('lt',10)) ;
    

    The query conditions are:

    (`id` > 1) AND (`id` < 10)
    


  • OR

    $map['id'] = array(array('gt',3),array('lt',10), 'or') ;
    

    The query conditions are:

        (`id` > 3) OR (`id` < 10)
    


  • AND

    $map['id']  = array(array('neq',6),array('gt',3),'and'); 
    

    The query conditions are:

        (`id` != 6) AND (`id` > 3)
    

    The last one can be an AND, OR or XOR operator. If not written, the default is an AND operation.
    The condition of interval query can support all expressions of ordinary query, that is to say, expressions like LIKE, GT and EXP can support. In addition, interval queries can support more conditions, as long as the conditions for a field can be written together.

For example:

    $map['name']  = 
        array(array('like','%a%'), 
        array('like','%b%'), 
        array('like','%c%'), 
        'ThinkPHP','or'); 


The final query condition is:

    (`name` LIKE '%a%') OR (`name` LIKE '%b%') OR (`name` LIKE '%c%') OR (`name` = 'ThinkPHP')


Composite query

The main body of the combined query still uses array query, only adding some special query support, including string pattern query (_string), compound query (_complex), request string query (_query). The special query in the mixed query can only define one query at a time. Because of using array index method, the special query with the same index will be overwritten.

  • String pattern query

    • _string

      Array conditions can also be used in conjunction with string conditions

      For example:

      $User = M("User"); // Instantiate User Objects
      $map['id'] = array('neq',1);
      $map['name'] = 'ok';
      $map['_string'] = 'status=1 AND score>10';
      $User->where($map)->select(); 
      

      The final query condition is:

      ( `id` != 1 ) AND ( `name` = 'ok' ) AND ( status=1 AND score>10 )
      
  • Request string query mode

    • _query

      Request string query is a method similar to URL parameterization, which can support simple conditional equality judgment.

      $map['id'] = array('gt','100');
      $map['_query'] = 'status=1&score=100&_logic=or';
      

      The query conditions are:

      `id`>100 AND (`status` = '1' OR `score` = '100')
      


Composite query

  • Compound query is equivalent to encapsulating a new query condition and then merging it into the original query condition, so it can complete more complex query condition assembly.

    • _complex
      For example:

      $where['name']  = array('like', '%thinkphp%');
      $where['title']  = array('like','%thinkphp%');
      $where['_logic'] = 'or';
      $map['_complex'] = $where;
      $map['id']  = array('gt',1);
      

      The query condition is

          ( id > 1) AND ( ( name like '%thinkphp%') OR ( title like '%thinkphp%') )
      

      Composite queries are defined by using _complex as a sub-query condition. With previous query methods, more complex query conditions can be formulated very flexibly.

      Many query methods can be converted to each other. For example, the above query conditions can be changed to:

      $where['id'] = array('gt',1);
      $where['_string'] = ' (name like "%thinkphp%")  OR ( title like "%thinkphp") ';
      

      The final generated SQL statements are consistent.


Multiple calls

  • Since version 3.1.3, where method supports multiple calls, but string conditions can only occur once

    For example:

    $map['a'] = array('gt',1);
    $where['b'] = 1;
    $Model
        ->where($map)
        ->where($where)
        ->where('status=1')
        ->select();
    

    Multiple array conditional expressions will eventually merge, but string conditionals only support once.




where() supplement
  • And count() statistics

    M('User')
        ->where('phone='.$phone)
        ->count();
    
    • count(): Number of statistical rows
    • max(): Statistics the maximum data for a field
    • min(): Statistical minimum data for a field
    • avg(): Statistics the average data of a field
    • sum(): Statistics the sum of data in a field

    Reference material: Statistical query

  • Only one query with find()

    $User
        ->where('phone='.$data['phone'])
        ->find();
    
  • With setInc() field and new

     if($User->add($data)){
        M('Role')
            ->where("role_type")
            ->setInc('role_num');
        }
    

    ps:
    where must be used in conjunction with a coherent operation

     $User = M("User"); // Instantiate User Objects
     $User->where('id=5')->setInc('score',3); // User's integral plus 3
     $User->where('id=5')->setInc('score'); // User's integral plus 1
     $User->where('id=5')->setDec('score',5); // User's integral minus 5
     $User->where('id=5')->setDec('score'); // User's integral minus 1
    

    The setInc. and setDec methods of 3.0 have been upgraded. They are very useful in increasing membership points and login times.

    Reference link: Thinkphp 3.0 adds setInc. and setDec methods

  • Update data with seve()

    where("id='{$userid}'")
        ->save($data);
    

    Note: To update data using save() method, you must specify update conditions or include primary key fields in the updated data.

    Reference material ThinkPHP Update Data Saving Method

  • Update the values of individual fields with setField()

    $User
        ->where("id='{$userid}'")
        ->setField('online','0');
    

    Reference material: The setField method updates the values of individual fields

  • Specify query fields with find () and field ()

     $store
        ->where('userid='.$userid)
        ->field('id,certification')
        ->find();
    
  • multi-table query

    • join

      $Follow
      ->alias('c')
      ->join('USER u ON c.c_bei= u.id')
      ->where("c.c_zhu='{userid}'")  
          ->field('c.c_bei,u.id as accountid,u.sex,u.nickname,u.head as photo,u.message')  
          ->limit(page,$number)
      ->select();

    • table

      Model  
            ->table('zca_user user,zca_ol ol')  
            ->where("ol.ol_num = {live_id} AND ol.ol_man = user.id AND ol.status = '1'")
      ->count();

    1. Examples of native queries:

    $Model = new Model();
    $sql = 'select a.id,a.title,b.content from think_test1 as a, think_test2 as b where a.id=b.id '.$map.' order by a.id '.$sort.' limit '.$p->firstRow.','.$p->listRows;
    $voList = $Model->query($sql);
    

    2. An example of join() method:

    $Model
        ->join('work ON artist.id = work.artist_id')
        ->join('card ON artist.card_id = card.id')
        ->select(); 
    

    3. table() method example:

    $list = $user
            ->table('user_status stats, user_profile profile')
            ->where('stats.id = profile.typeid')
            ->field('stats.id as id, stats.display as display, profile.title as title,profile.content as content')
            ->order('stats.id desc' )->select();
    

    Reference material: ThinkPHP multi-table query

  • Direct Writing Conditions with AND

    M('System')
       ->where("`userid`={$userid} AND `acceptid`={$user_author['prd_author']} AND `worksid` = {$got} AND `type`= '1'")
       ->count();
    
  • delete

    $Praise
        ->where($map)
        ->delete();
    
  • sort

    $Photo
        ->field('url')
        ->where("album='{$albumid}'")
        ->order('add_time asc')
        ->find()['url']; 
    

2017/1/14 22:43:24

Statistical query

  • In application, we often use some statistical data, such as the current number of users (or meet certain conditions), the maximum score of all users, the average score of students, etc. ThinkPHP provides a series of built-in methods for these statistical operations:

    count(): Number of statistical rows

    max(): Statistics the maximum data for a field

    min(): Statistical minimum data for a field

    avg(): Statistics the average data of a field

    sum(): Statistics the sum of data in a field

    The above statistical query methods are independent and support coherent operation.

  • count()

    The count() method is used to count rows.

    Example:

        public function read(){
         $Dao = M('User');
        // Get the number of users:
         $userCount = $Dao
                    ->count();
        //SELECT COUNT(*) AS tp_count FROM user LIMIT 1         
    
        // Adding conditions:
         $userCount2 = $Dao
                    ->where('uid > 10')
                    ->count();
        //SELECT COUNT(*) AS tp_count FROM user WHERE uid > 10 LIMIT 1
    
         $Model
            ->table('pre_user user,pre_ol ol')
            ->where("ol.ol_num = {$live_id} AND ol.ol_man = user.id AND ol.status = '1'")
            ->count();
    
            $this->assign('userCount', $userCount);
            //  Statistical data can be output directly in the template:
            //  There are users {$userCount} in common.
            $this->display();          
    
    
        }
    
  • max()

    The max() method is used to calculate the maximum data of a field.

    Statistical user maximum integral example:

    $maxScore = $Dao->max('score');
    

    The actual execution of the SQL is as follows:

    SELECT MAX(score) AS tp_max FROM user LIMIT 1 
    
  • min()

    min() counts the smallest data in a field.

    Get an example of the minimum integral of a user whose integral is greater than 0:

    $minScore = $Dao->where('score>0')->min('score');
    

    The actual execution of the SQL is as follows:

    SELECT MIN(score) AS tp_min FROM user WHERE score>0 LIMIT 1
    
  • avg()

    avg() counts the average data of a field.

    Get an example of average user integrals:

    $avgScore = $Dao->avg('score');
    

    The actual execution of the SQL is as follows:

    SELECT AVG(score) AS tp_avg FROM user LIMIT 1
    
  • sum()

    sum() counts the sum of data in a field.

    The sum of the scores of the top 10 users in the statistical score ranking:

    $sumScore = $Dao->order('score DESC')->limit('10')->sum('score');
    

    The actual execution of the SQL is as follows:

    SELECT SUM(score) AS tp_sum FROM user ORDER BY score DESC LIMIT 10 
    

    All statistical queries are the same as the select() method. They all support the use of coherent operations and add different query conditions according to the actual situation.







add method adds new data

  • Use add method to add new data to database.

    $User = M("User"); // Instantiate User Objects
    $data['name'] = 'username';
    $data['email'] = 'username@gmail.com';
    $User->add($data);
    

    Or use the data method to operate coherently

    $User->data($data)->add();
    
  • String mode

    The string format is used as follows:

    $Model = M('User');
    $data = 'name=zy2333&email=zy2333@qq.com';
    $Model->data($data)->add();
    

Reference material: data method






addall batch insertion

  • The difference between add() and addAll()

    • add() is a record single insert

      $User = M("User"); // Instantiate User Objects
      $data['name'] = 'ThinkPHP';
      $data['email'] = 'ThinkPHP@gmail.com';
      $User->add($data);
      
    • addAll() is record batch insertion

      $dataList[] = array('name'=>'thinkphp','email'=>'thinkphp@gamil.com');
      $dataList[] = array('name'=>'onethink','email'=>'onethink@gamil.com');
      $User->addAll($dataList);
      

      Note: The subscript is 0, otherwise it may fail.

      mysql:

      INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
      

      In many cases, try to choose batch insertion instead of circular insertion, otherwise your database will not be able to eat and hang up.
      But if you want to take it for granted to put all the data into an array and add All, you will also face hanging up. Why?
      The reason is that the configuration of the max_allowed_package variable in mysql limits the length of the uploaded sql statement. In mysql configuration, just configure it a little larger.

      max_allowed_packet = 100M
      

      At the same time, the length of batch insertion should be limited when inserting data. After all, you don't know when the data will become millions.

    - addAll instance

               //Upload album pictures (more)
               public function prd_photo()
               {
                    $upload = new \Think\Upload();// Instantiate upload classes
                    $upload->maxSize   =     3145728 ;// Set attachment upload size
                    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// Set the attachment upload type
                    $upload->savePath  =      './Public/Uploads/'; // Set up the attachment upload directory//upload files
                    $info   =   $upload->upload();
                    if(!$upload->rootPath){
                        mkdir($upload->rootPath,0777,true);
                    }
                    if(!$info) {
                        $rest['status'] = false;
                        $rest['message'] = 'Upload failure';
                        $rest['error'] = $this->error($upload->getError());
    
                        echo json_encode($rest,JSON_UNESCAPED_UNICODE);exit;
                    }else{
                        $dataList = [];
                        foreach($info as $file){
                            $dataList[] = [
                                'author' => $_REQUEST['userid'],
                                'album' => $_REQUEST['album'],
                                'url' => '/Uploads/photo/'.$file['savepath'].$file['savename'],
                                'add_time' => time(),
                            ];
                        }
                        $Photo=M('Photo');
    
                     $Arr = $Photo->addAll($dataList);
    
                        if($Arr){
                         $rest['status'] = true;
                         $rest['message'] = 'Upload success';
                        echo json_encode($rest,JSON_UNESCAPED_UNICODE);exit;
                        }
                    }
             }
    


  • The null value cannot appear in the addAll method, otherwise other data will move forward automatically, causing the addition to fail. Give an example:

            [
                {
                     "appId": 1,
                     "serviceId": 2,
                    "createUser":null,
                    "status": 1,
                     "priority": 2
                 }
            ]
    

Where the createUser field is null, the sql statement at insertion becomes insert into va_problem (appId, serviceId, createUser, status, priority) values (1, 2, 1, 2). The null value is missing, causing the insert to fail, which should be a bug in ThinkPHP 3.2.3.

Reference material Carefully use the addAll method in ThinkPHP,On the Failure of addAll()







Update data save method

  • Use save() method to update database

    $User->where("id='{$userid}'")->save($data);
    

    Tips:

    In order to ensure the security of the database and avoid errors in updating the entire data table, if there are no updating conditions and the data object itself does not contain the primary key field, the save method will not update the records of any database.

    Therefore, to update data using the save() method, you must specify an update condition or include a primary key field in the updated data.

  • If it is form data, you can also use create() method to create data objects to update data:

    public function update(){
    header("Content-Type:text/html; charset=utf-8");
    $Dao = D("User");
    
    if($vo = $Dao->create()) {
            $result = $Dao->save();
            if($result !== false){
                echo 'Data update is successful!';
            }else{
                echo 'Data update failed!';
            }
        }else{
           $this->error($Form->getError());
        }
    }
    

Reference material: create() method







create() method

  • After creating () the data object is created, the submitted form data is automatically collected. Form data may need to be processed (e.g. encrypted password) to be written to the data table, so the member attribute values of data objects can be modified or added or removed.

    Tips:

    create() creates data objects that are stored in memory and can be modified before executing add() or save().
    In the example above, the behavior of the create() method is consistent with that of the date() method. But the date() method is only a simple way to create data objects, but the create() method also has:

    step Explain Return
    1 Get the data source (default is the POST array)  
    2 Verify data source legitimacy (non-array or object filters) Failure returns false
    3 Check field mapping  
    4 Judge submission status (add or edit) automatically by primary key  
    5 Automatic data validation Failure returns false
    6 Form token validation Failure returns false
    7 Form data assignment (filtering illegal fields and string processing)  
    8 Automatic data completion  
    9 Generate data objects (stored in memory)  
    • Modify before executing an inbound action (add() or save())

      User=M('User'); User - > create (); and // Create User data objects
      User> status = 1; // Set default user status User - > create_time = time (); // / Set user creation time
      User - > add (); // Write user objects to the database

    • Automatic Verification and Filling

    Before writing a form to a data table, there are often some checks and processing of the data (whether the submitted username meets the requirements) such as password encryption in the example and the acquisition of the current timestamp. The create() method supports automatic data validation and completion.

    Create the UserModel.class.php file in the LibModel directory (User is the model object created, and corresponds to the prefix_user table), and add the rules of automatic validation and automatic filling:

    class UserModel extends Model{
        // Automatic Verification Settings
        protected $_validate = array(
        array('username','require','User name must be filled in!',1),
        array('email','email','The mailbox format is wrong!',2),
        array('username','','User name already exists!',0,'unique',1),
        );
        //Automatic Filling Settings
        protected $_auto = 
        array(
            array('regdate','time',self::MODEL_INSERT,'function'),
            array('password','md5',self::MODEL_INSERT,'function'),
        );
    }
    

    Change insert2 operation to:

    public function insert2(){
    header("Content-Type:text/html; charset=utf-8");
        $Dao = D("User");
    
        if($Dao->create()){
            if($lastInsId = $Dao->add()){
                echo "insert data id For: $lastInsId";
            } else {
                echo "Data Writing Error!";
            }
        }else{
            exit($Dao->getError().' [ <a href="javascript:history.back()">Return</a> ]');
        }
    }
    

    If the submitted data does not meet the validation requirements (e.g. the user name exists), then create() fails to create the data object (return FALSE), $Dao - > getError () prints out the prompt information set in the automatic validation settings rule: the user name already exists!

    If the validation rules pass, the system will automatically fill in the settings, MD5 encryption of the form password and the current timestamp to fill in the create() data object.
    Therefore, D method with create() is very intelligent and powerful, and the proper use of it can achieve the goal of rapid development with half the effort.

    Tips
    D method cooperates with create(), because of its powerful function, it also loses some efficiency. M method + data() mode is recommended when business logic is not complex.
    Crea () accepts POST data by default. To accept other types of data, you only need to specify in parameters, such as accepting GET data: create($_GET)

    The create method defaults to $_POST data if no value is passed. If the variable content submitted by the user contains executable html code, please filter it manually.

    $_POST['title'] = "<script>alert(1);</script>";
    

    Illegal html codes can be coded using html specificalchars to prevent user-submitted html codes from being executed during presentation. Here are two security approaches.

    $_POST['title'] = htmlspecialchars($_POST['title']);
    M('User')->create();
    $data['title'] = $this->_post('title', 'htmlspecialchars');
    M('User')->create($data);
    

    Reference material: create() method creates data,Intelligent Writing create Method for Form Data,ThinkPHP 3.1 Quick Start (16) Security







data method

  • Write operation

    Usually, we generate data objects by creating method or assignment method, and then write them to the database, for example:

     $Model = D('User');
     $Model->create();
    // Specific automatic generation and validation judgments are omitted here.
     $Model->add();
    

    Or assign values directly to data objects, such as:

    $Model = M('User');
    $Model->name = 'zy';
    $Model->email = 'zy2333@qq.com';
    $Model->add();
    

    Then the data method directly generates the data object to be operated on, for example:

    $Model = M('User');
    $data['name'] = 'zy';
    $data['email'] = 'zy2333@qq.com';
    $Model->data($data)->add();
    

    Note: If we use both create method and data to create data objects, the later method is valid.

    The data method supports arrays, objects, and strings in the following way:

     $Model = M('User');
     $obj = new stdClass;
     $obj->name = 'zy';
     $obj->email = 'zy2333@qq.com';
     $Model->data($obj)->add();
    

    The string format is used as follows:

      $Model = M('User');
      $data = 'name=zy&email=zy2333@qq.com';
      $Model->data($data)->add();
    

    You can also directly pass in data objects in the add method to add new data, for example:

      $Model = M('User');
      $data['name'] = 'zy';
      $data['email'] = 'zy2333@qq.com';
      $Model->add($data);
    

    But in this way, data parameters can only use arrays.

    Of course, the data method can also be used to update data, for example:

     $Model = M('User');
     $data['id'] = 8;
     $data['name'] = 'zy';
     $data['email'] = 'zy2333@qq.com';
     $Model->data($data)->save();
    

    Of course, we can also use it directly:

     $Model = M('User');
     $data['id'] = 8;
     $data['name'] = 'zy';
     $data['email'] = 'zy2333@qq.com';
     $Model->save($data);
    

    Similarly, data parameters can only be passed into arrays at this time.

    When the save method is called to update the data, it automatically determines whether the primary key value exists in the current data object, and if so, it automatically acts as the update condition. That is to say, the following usage is equivalent to the above one:

     $Model = M('User');
     $data['name'] = 'zy';
     $data['email'] = 'zy2333@qq.com';
      $Model->data($data)->where('id=8')->save();
    
  • Read operation

    In addition to write operations, data methods can also be used to read current data objects, such as:

     $User = M('User');
     $map['name'] = 'zy';
     $User->where($map)->find();
     // Read the current data object
     $data = $User->data();
    




2017/1/15 21:28:15




find method queries a data record

  • The find() method is similar to the use of select(), except that the find() always queries only one data, that is, the system automatically adds LIMIT 1 restrictions.

    When confirming that the data record of the query can only be one record, it is recommended to use find() method to query, such as user login account detection:

    public function chekUser(){
        header("Content-Type:text/html; charset=utf-8");
         $Dao = M("User");
    
        // Constructing query conditions
        $condition['username'] = 'Admin';
        $condition['password'] = MD5('123456');
        // Query data
        $list = $Dao->where($condition)->find();
    
        if($list){
        echo 'Account number is correct.';
        }else{
        echo 'Account number/Password error';
        }
    }
    

    Another difference from select() is that find() returns a one-dimensional array, which can output the values of array units directly in the template without using labels such as volist to loop out:

    {$list['username']}
    
  • find() primary key query

    When the condition parameter of the find() query is the primary key of the table, the parameters can be written directly into the method, such as:

    $Dao = M("User");
    $list = $Dao->find(1);
    

    The primary key of user table is uid. This example will query the data of uid=1. This is one of the implementation of ActiveRecords mode. It is concise and intuitive.

The setField method updates the values of individual fields

  • The setField() method is used to update the values of individual fields.

    Example:

    public function update(){
        header("Content-Type:text/html; charset=utf-8");
        $Dao = M("User");
    
        $result = $Dao->where('uid = 2')->setField('email','zy2333@163.com');
    
        if($result !== false){
         echo 'Data update is successful!';
     }else{
            echo 'No data update!';
        }
    }
    

    The SQL statement executed by the above example is:

    UPDATE user SET email='zy2333@163.com' WHERE uid = 2
    
  • Update multiple fields

    The setField() method supports updating multiple fields at the same time, just passing in array parameters:

    public function update(){
     header("Content-Type:text/html; charset=utf-8");
        $Dao = M("User");
    
        $result = $Dao->where('uid = 28')->setField(array('username','email'),array('zy2333','zy2333@163.com'));
    
        if($result !== false){
            echo 'Data update is successful!';
        }else{
            echo 'No data update!';
        }
    }
    
    • The syntax of the setField() method is:

      setField(fields, value, condition='')
      

    So setField() can't be passed into setField() by constructing an array of data, just like the save() method. Instead, fields and values that need to be updated need to be passed into setField() methods, respectively.

Posted by GateGuardian on Sat, 30 Mar 2019 22:21:28 -0700