thinkphp Modifying and deleting data

Source: Internet
Author: User
Tags smarty template

1. In the controller Maincontroller, write a method that invokes the data in the nation table.

Public Function Zhuyemian ()    {        $n = D ("Nation");//Create a Nation object        $attr = $n->select ();//query all data, return a two-dimensional array.        $this->assign ("n", $attr);//Register the two-dimensional array in the template display.        $this->show ();//Invoke Template display    }

2. Create a new template file to display zhuyemian.html

<body><table width= "100%" border= "1" cellpadding= "0" cellspacing= "0" >    <tr>        <td> codename </td>        <td> name </td>        <td> action </td>    </tr>    <foreach name= "n" Item= "V" ><!--loop out the table information with the foreach built-in label tag, and V for the decimal group. -    <tr>        <td>{$v .code}</td><!--Note that this is {$v. code} instead of {$v [0]} because the data found is a two-dimensional associative array--        <td>{$v .name}</td>        <td><a href= "__controller__/xiugai/code/{$v. Code}" > Modify </a ><!--because it is in the same controller, you can directly use __controller__ to obtain the path of the controller, followed by the Xiugai method, then write the name of the value to be passed, and finally write the value. Path can not be written to die, to write dynamic, all the paths in the template as far as possible not to write to death, all with constant information to write.            --<a href= "__controller__/shanchu/code/{$v. Code}" onclick= "return confirm (' OK to delete? ') > Delete </a></td><!--point to the Delete method and pass a code value, the code value is also {$v .code}-->    </tr>    </ Foreach></table></body>

3. Display Page

4. Make changes to display page xiugai.html

<body><form action= "__action__" method= "POST" ><!--action to point to the current controller, as long as the link, the path must be written with constant information, do not write dead-->< Input  type= "hidden" name= "code" value= "{$nation. Code}"/>    <div> Name: <input type= "text" name= "name "Value=" {$nation. Name} "/></div>    <div><input type=" Submit "value=" Modify "/></div></ Form></body>

5. Write the modification method inside the controller Maincontroller

Public Function Xiugai ($code = "")//xiugai method to implement 2 logic, 1 is to display the page, 2 is to modify the information.    {        $n = D ("Nation");        if (empty ($_post))//To determine whether the POST array is empty, if it is empty, the page is displayed.        {            $nation = $n->find ($code);//find only 1 data, and is a one-dimensional array.            $this->assign ("Nation", $nation);            $this->show ();        }        Else//post array does not empty the Modify logic        {            //modify            $n->create ();//automatic collection of forms, create collection form is smart, other forms are automatically ignored, For example, when registering an account will allow the user to enter 2 password, so that you need to set 2 password box in a column name, the other one casually set a non-column name, this is not the column name of the password box will be automatically ignored. So you don't need to submit a form without a column name.            $r = $n->save (); The//save method is the modified method            if ($r)            {                $this->success ("Modified successfully", "Zhuyemian");//After a successful modification, prompt "Modify succeeded" and jump to zhuyemian.html            }            else            {                $this->error ("Modify failed");//Modify Failure Prompt "Modify failed. "            }        }    }

6. Click Edit, jump to modify page, and pass the corresponding code value.

After the modification is successful, click "Modify".

7. Write the Delete method inside the controller Maincontroller

Public Function Shanchu ($code)//Delete method also requires a code    {        $n =d ("Nation");//object        $r = $n->delete ($code);// Call the Delete method, directly put the primary key value as a parameter in () can be.        if ($r)        {            $url = u ("Zhuyemian"),//Use the U method to create a path            $this->success ("delete Success", $url);//Put the path of the build in the page to jump, attention can not directly also page, error.        }        else        {            $this->error ("delete failed");        }    }

thinkphp3.2.3 User Manual

8. Templates

(1) Variable output

The variable output is the same as the Smarty template, which is {$name}.

(2) Output of system variables

  1. {$Think.server.script_name} // 输出$_SERVER[‘SCRIPT_NAME‘]变量
  2. {$Think.session.user_id} // 输出$_SESSION[‘user_id‘]变量
  3. {$Think.get.pageNumber} // 输出$_GET[‘pageNumber‘]变量
  4. {$Think.cookie.name} // 输出$_COOKIE[‘name‘]变量
  5. {$Think.const.MODULE_NAME}//输出常量
  6. {$Think.config.db_charset}//输出配置参数
  7. {$Think.lang.page_error}//取语言

(3) using a function (called with |)

  1. {$data.name|md5}//$data.name调用md5
  2. {$create_time|date="y-m-d",###}//Indicates that the date function passed two parameters, each parameter is separated by commas, here the first argument is, the second argument is the y-m-d variable to be output before, create_time because the variable is the second parameter, so you need to use # # #标识变量位置, the result of the compilation is:<?php echo (date("y-m-d",$create_time)); ?>

(4) Default value output

    1. {$Think.get.name|default="名称为空"}//默认值输出使用的是default,实际上也是一个函数。

(5) Using operators

Use operators for template output and also include "+" "" "*" "/" and "%".

(6) Template inheritance

Template inheritance is a more flexible template layout, template inheritance is different from template layout, and even should be on the top of the template layout. Template inheritance is not difficult to understand, just like the inheritance of a class, a template can also define a base template (or layout), where the relevant block (block) is defined, and then inherit (extend) the template in the base templates can be overloaded with the blocks defined in the underlying template.

Example: A. How to do a parent class

Public Function Fu ()    {        $this->show ();    }

B. Do the display page of the parent class

<title> Untitled document </title><block name= "tou" ></block><!--the area of the head, where the subclass file can inherit the head--></ Head><body><div style= "width:100%; height:200px;  padding:0px; line-height:1.5; Color:rgb (0, 0, 255); FONT-SIZE:12PX!important; " >></div><block name= "Neirong" ></block><!--do body area, subclass file can inherit Body--><div style here = "width:100%; height:100px;  padding:0px; line-height:1.5; Color:rgb (0, 0, 255); FONT-SIZE:12PX!important; " >></div></body>

C. Ways to do sub-templates

Public Function Zi ()    {        $this->show ();    }

D. Do the display page of the sub-category

<extend name= "Fu"/><!--extend represents the inheritance meaning, name inside is the name of the template to inherit--><block name= "Tou" >    <title> Test sub-template </title></block><block name= "Neirong" >    <div style= "width:100%; height:300px  ; padding:0px; line-height:1.5; Color:rgb (0, 0, 255); FONT-SIZE:12PX!important; " >></div></block>

The displayed page is a sub-page, but the head and tail inherit the parent page.

(7) Include file

Include other template files in the current template file using the Include tag, label usage:

    1. <include file="Public/header" /> // 包含头部模版header
    2. <include file="Public/menu" /> // 包含菜单模版menu
    3. <include file="Blue/Public/menu" /> // 包含blue主题下面的menu模版

(8) Compare labels

Their usage is basically the same, the difference is that the conditions are different, and all the comparison labels can be used with the else tag.

For example:<eq name="name" value="value">value</eq>表示name变量的值等于value就输出

(9) Import label

The traditional way to import external JS and CSS files is to use the template file directly:

    1. <script type=‘text/javascript‘ src=‘/Public/Js/Util/Array.js‘>
    2. <link rel="stylesheet" type="text/css" href="/App/Tpl/default/Public/css/style.css" />

The system provides a special label to simplify the above import:

The first is the import label, which uses the namespace-like method of an import function similar to thinkphp, for example:

    1. <import type=‘js‘ file="Js.Util.Array" />The type attribute is JS by default, so type= ' JS ' can not be written.

You can also support batch import of multiple files, for example:

    1. <import file="Js.Util.Array,Js.Util.Date" />

9.SESSION and Cookies

Session in thinkphp does not need to add session_start () Open, in the configuration file has a configuration is true by default.

Session Store data

    1. session(array(‘name‘=>‘session_id‘,‘expire‘=>3600));

Session initialization setting method does not need to call manually, after the initialization of the Think\app class is called automatically, usually the project only needs to configure SESSION_OPTIONS parameters, SESSION_OPTIONS The parameter is set to an array, the supported index name and the previous session initialization parameters are the same.

By default, after initialization the system will automatically start the session, if you do not want the system to automatically start the session, you can set SESSION_AUTO_START to False, set the way:

    1. ‘SESSION_AUTO_START‘ =>false

The session assignment is relatively straightforward and is used directly:

    1. session(‘name‘,‘value‘); //设置session

Session value using:

    1. $value = session(‘name‘);
    2. // 获取所有的session 3.2.2版本新增
    3. $value = session();

Delete the value of a session using:

    1. session(‘name‘,null); // 删除name

To determine if a session value has been set, you can use the

    1. // 判断名称为name的session值是否已经设置
    2. session(‘?name‘);

Cookie settings
    1. cookie(‘name‘,‘value‘); //设置cookie
    2. cookie(‘name‘,‘value‘,3600); // 指定cookie保存时间

You can also support the way in which parameters are passed in to complete complex cookie assignments, the following is a 3,600-second validity period for the value of the cookie, plus a cookie prefix THINK_

    1. cookie(‘name‘,‘value‘,array(‘expire‘=>3600,‘prefix‘=>‘think_‘))

Getting a cookie is simple, no matter how the cookie is set, only needs to use:

    1. $value = cookie(‘name‘);

If the cookie prefix is not set, the equivalent

    1. value = $_COOKIE[‘name‘];

To delete the value of a cookie, use:

    1. cookie(‘name‘,null);

To delete all cookie values, you can use:

    1. cookie(null); // 清空当前设定前缀的所有cookie值
    2. cookie(null,‘think_‘); // 清空指定前缀的所有cookie值

thinkphp Modifying and deleting data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.