thinkphp Framework: Conditional database queries, additional knowledge of the TP framework

Source: Internet
Author: User
Tags session id zts smarty template

The previous essay is a basic operation, you can now do some advanced operations, such as conditional query data, with paged condition query data

Query data for one conditions

Querying data is naturally the first to display the data and then to query the data based on the criteria

(1) Display the data of the table

This method I still write in the Homecontroller.class controller file

(1.1) wrote a method Shouye ()

Public Function Shouye () {    $n = M ("Nation");//table in database    $arr = $n->select ();  Query all data in the table    $this->assign ("Shuju", $arr);  Injecting a two-dimensional array into a variable    $this->show ();  Show Data}

(1.2) After the method has been written, the following is the display page, the name and method name consistent

Here we use a table to show the data

<table width= "50%" border= "1" cellpadding= "0" cellspacing= "0" >    <tr>        <td> code </td>        <td> name </td>        <td> actions </td>    </tr>
<!--Note: The loop here does not have {} This is the difference from the Smarty template-- <foreach name= "Shuju" item= "V" > <!--parameter name is the injected name in the PHP page , item is the amount of the assignment- <tr> <td>{$v .code}</td> <!--This is the code column that is displayed-- <td>{$ V.name}</td> <!--This is the Display Name column-- <td> action </td> </tr> </foreach> </table>

The following run looks at the effect: note the Address bar writing: Http://localhost/tp/index.php/Home/Home/shouye

(2) Add query criteria

(2.1) This will add the query text box and the query button, we added in front of the table

Here to write with the form, because the submission, so with the form to write

<form action= "__action__" method= "POST" >    <div>        Query by name: <input type= "text" name= "name"/>        <input type= "submit" value= "inquiry"/>    </div></form>        

Look at the display effect

(2.2) After the display, is the back of the processing page

This query and add, modify the logical processing method is not the same, there is no need to determine the

Public Function Shouye () {    $TJ = "1=1"; Conditional constant Set    if (!empty ($_post["name"]))  //Determine if the name passed over is not empty    {        $name = $_post["name"];          $TJ = "Name like '%{$name}% '";  Modify the value of the $TJ    }    $n = M ("Nation");    $arr = $n->where ($TJ)->select ();  Because it is a TP framework, you can call this condition directly, using the Where () method    $this->assign ("Shuju", $arr);    $this->show ();}        

Run it like this, and then look at the results

Query the "Back" information, you can implement this query

(2.3) You can add pagination in this query, that is, the display of pagination

1. Here we refer to the previously written page paging class, first put the page's class under its own module, I put it here

Open the class file and modify the namespace as follows:

And then close it.

2. Call the page class in the Shouye () method

2.1 First to call this page class

2.2 This class has two parameters: the total number of pages, the number of bars displayed

$page = new \home\shuju\page ($zts, 2);  First parameter: The total number of data bars, and the second parameter is a display of several

2.3 Total number of bars: query is also to show the total number of bars

$zts = $n->where ($TJ)->count ();  The total number of bars must also include the query

2.4 In limit here to modify the source file,

$page->limit;  LIMIT 10,3

This will be more than a limit, then in the page.class.php source files can be deleted

2.5 Add this limit ($page->limit) method when querying all conditions

$arr = $n->where ($TJ)->limit ($page->limit)->select ();

2.6 Injection variables (injecting information from the page to display information)

$this->assign ("Fenye", $page->fpage ());  Page display information for fpage pagination

Look at the total of this Shouye () method, above the synthesis

Public Function Shouye () {$tj = "1=1";    if (!empty ($_post["name"])) {$name = $_post["name"];  $TJ = "Name like '%{$name}% '";  } $n = M ("Nation"); $zts = $n->where ($TJ)->count ();  The total number of bars should also include the query $page = new \home\shuju\page ($zts, 2);  First parameter: The total number of data bars; The second parameter is a display of several//$page->limit;  LIMIT 10,3 $arr = $n->where ($TJ)->limit ($page->limit)->select ();  This is the pagination displayed $this->assign ("Shuju", $arr);  Injected variables (total data) $this->assign ("Fenye", $page->fpage ());  Inject variable (display information for pagination) $this->show ();}

2.7 On the Display page, show this variable

<div>{$fenye}</div>

See First run results, there is paging information

However, there is a flaw, that is, when querying a condition, the first is that the total number of bars shown is the correct amount, but the following is wrong, then is to modify the code

Note: Change the way data is transferred (post is modified to get)

3. The text box of the query displays the default value

Here, under conditional constancy, define a name value of NULL, and then in the injected variable

In the text box that displays the page, add a value that is the previously injected variable

Attention:

1. Look at the code for the full PHP page

Public Function Shouye () {      $TJ = "1=1";      $name = "";    if (!empty ($_post["name"])) {$name = $_post["name"];  $TJ = "Name like '%{$name}% '";  } $n = M ("Nation"); $zts = $n->where ($TJ)->count ();  The total number of bars should also include the query $page = new \home\shuju\page ($zts, 2);  First parameter: The total number of data bars; The second parameter is a display of several//$page->limit;  LIMIT 10,3 $arr = $n->where ($TJ)->limit ($page->limit)->select ();  This is the pagination displayed $this->assign ("Shuju", $arr);  Injected variables (total data) $this->assign ("Fenye", $page->fpage ());  Inject variable (display information for pagination)      $this->assign ("name", $name);  Inject the value of name into the variable     $this->show ();}

2. Display the overall content of the page

<form action= "__action__" method= "get" >     <div>        Query by name: <input type= "text" name= "name"  Value= "{$name}"/>        <input type= "Submit" value= "Query"/>    </div></form><br/>< Table width= "50%" border= "1" cellpadding= "0" cellspacing= "0" >    <tr>        <td> code </td>        <td> name </td>        <td> action </td>    </tr>                <foreach name= "Shuju" item= "V" >        <tr>            <td>{$v .code}</td>            <td>{$v .name}</td>            <td> Operations < /TD>        </tr>    </foreach></table>        <div>{$fenye}</div>        

So the total effect is over.

After querying, the text box displays the name of the query, and the number of bars displayed is also transformed

Second, the data value method

1. Write a method for the data value difference: The normal get method to take value

Public Function Testget () {    echo $_get["name"];}

In the Address bar address of the browser, enter:

(1) followed by:? name = "Value"

1. Empty if no value is passed

Http://localhost/tp/index.php/Home/Home/testget

The output is empty:

2. Value-in-pass value

Http://localhost/tp/index.php/Home/Home/testget?name=%22%E4%BD%A0%E5%A5%BD%22

This will output: Hello

(2) The way behind the path:/name/value

In the Address bar, enter:

Http://localhost/tp/index.php/Home/Home/testget/name/qqqqqq

Output results

Note: Multiple values are/name/value/First Name/value

2. Assigning a value to a method

Public Function Testget ($code) {echo $code;}

 

Third, session method and Cookie method

(1) Session method

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

' Session_auto_start ' =>false

Shut down the project's public files after auto-start or by manually invoking or starting the session in the controller session_start session(‘[start]‘) .

2.session Value Assignment

Session (' name ', ' value ');  Set session

3.session judgment

Determine if the session value named name is already set to session ('? name ');

4.session Management

Session (' [Pause] '); Pause Session Write session (' [Start] '); Start Sessionsession (' [Destroy] '); Destruction of Sessionsession (' [Regenerate] '); Regenerate session ID

(2) Cookie method

Cookie settings

Cookie (' name ', ' value ');  Set Cookiecookie (' name ', ' value ', 3600); Specify the cookie save time

Four, template (ternary operation)

Templates can support ternary operators

{$status? ' Normal ': ' Error '} {$info [' status ']? $info [' msg ']: $info [' Error ']}

Note: Point syntax is not supported temporarily in the ternary operator.

V. Ajax return

To use Ajax, we'll refer to jquery, and we'll bring jquery in.

(1) I put in the public folder, create a new JS folder

(2) and then the display of the page to bring up this JS file

<script src= "__public__/js/jquery-1.11.2.min.js" ></script>

(3) See if this file was introduced

In the address bar of the browser, type: Http://localhost/tp/index.php/Home/Home/shouye

View source code view is not the introduction of

If you can show up after it's opened, it's a success.

(4) Write a method in the controller Chuli, let Ajax return to this method

Public Function Chuli () {   }

(5) I'm going to write Ajax.

<script type= "Text/javascript" > $.ajax ({url: "__controller__/chuli",  //handling method DataType: "Text", Success: function (data) {//Output after success}}) </script>

(6) The Chuli method page will write the return value.

Public Function Chuli () {    $this->ajaxreturn ("Hello", "eval");   Returns the value of the return value in the way that eval is the text way}

Note: If it is in the JSON/JSONP format, it is automatically encoded into a JSON string, and if it is XML, it is automatically encoded into an XML string, and if it is eval, only the string data is output.

Complete code for the display page:

<script type= "Text/javascript" >    $.ajax ({        URL: "__controller__/chuli",        dataType: "Text",        Success:function (data) {            alert (data);  return information            }    ) </script>        

Look at the effect:

It can also be an associative array of data, not write

Vi. Jump and redirect

(1) Page jump

The way to use it is simple

$User = M (' User '); Instantiate the User object $result = $User->add ($data); if ($result) {        //Set the address of the jump page after success, the default return page is $_server[' http_referer ']        $this->success (' New success ', ' user/list ');}    The default jump page of the else {//error page is to return to the previous page, usually without setting        $this->error (' new failed ');}

Note: The first parameter of the success and the error method indicates a prompt, the second parameter represents a jump address, and the third parameter is the jump time in seconds.

Operation completed 3 seconds to jump to/article/index$this->success (' Operation Complete ', '/article/index ', 3);//operation failed 5 seconds after jumping to/article/error$this-> Error (' Operation failed ', '/article/error ', 5);

Note: The jump address is optional, the default jump address for the success method is $_SERVER["HTTP_REFERER"] , the default jump address for the error method is javascript:history.back(-1); .

This is another knowledge and operation of the TP framework

thinkphp Framework: Conditional database queries, additional knowledge of the TP framework

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.