Commonly used form submission operations in ThinkPHP include the post method and the get method.
The post method is safer than the get method. If you use the get method, your submitted form, including account password and other information, will be displayed in the access path, while the post method will hide its data.
Rewrite the add method to determine whether it is a post request. If so, process the form submission. If not, display the template.
Extension: How to determine whether the request is a post?
Answer: We can use if($_POST) to judge, but in ThinkPHP the system encapsulates several commonly used constants for us. We can directly use constants to judge. Common constants are as follows:
IS_POST If the request is post, the value of IS_POST is true, otherwise it is false
IS_GET
IS_AJAX If the request is ajax, the value of IS_AJAX is true, otherwise it is false
IS_CGI
IS_PUT
…
Instructions on data reception:
When we used $_POST to receive data before, In ThinkPHP, we can use the I method (quick method) to receive data. The I method can receive any type of input (post, get, request, put, etc.), and the system comes with a method to prevent SQL injection by default (using PHP's built-in function htmlspecialchars).
The variable type is similar to get, post, etc.
The variable name refers to the subscript of the specific element in $_GET or $_POST.
Default value: If the original content becomes an empty string after using the filtering method, the default value will be used instead.
Filtering method: It is a supplement to the htmlspecialchars provided by ThinkPHP by default. The function name can be built-in in PHP or in the function library.
Extra instructions: What if you want to receive the entire array?
If you want to receive all the data, you don’t need to write the variable name, you can write it as I(‘get.’);
<?php public function add(){ if(IS_POST){ //处理表单提交 $post = I('post.'); //添加数据 //实例化模型 $model = M('Dept'); $result = $model -> add($post); //判断返回值 if($result){ //添加成功 $this -> success('添加成功',U('showList'),5); }else{ $this -> error('添加失败'); } }else{ //实例化模型 $model = M('Dept'); //查询操作 $data = $model -> where('pid = 0') -> select(); //变量分配 $this -> assign('data',$data); //展示模板 $this -> display(); } }
Recommended tutorial: thinkphp tutorial
The above is the detailed content of Commonly used methods to submit forms in thinkphp. For more information, please follow other related articles on the PHP Chinese website!