search

ThinkPHP data paging

Jun 08, 2018 pm 03:28 PM
thinkphpExample tutorialQuick startData paging

This article mainly introduces the data paging implementation process of the ThinkPHP quick start tutorial. Friends who need it can refer to it

Data paging may be one of the most commonly used functions in web programming. ThinkPHP implements paging function very simply. This can be achieved by just defining a few parameters. And it is also very easy to expand.

Let’s implement ThinkPHP’s paging program from scratch.

1. First, we have to create a database for paging testing. The test.sql code is as follows.

CREATE TABLE `test` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` char(100) NOT NULL,
`content` varchar(300) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=27 ;
INSERT INTO `test` (`id`, `name`, `content`) VALUES
(19, '123', '123'),
(20, '1231', '123123123'),
(21, '123123', '123123123'),
(26, '24', '123123'),
(25, '321123', '321123'),
(24, 'age', 'age'),
(23, '123123', '123123'),
(22, '213', '123');

2. Next, we have to create a new ThinkPHP project. The new version of tp has built-in automatic project directory generation function.
Create a new test folder under htdocs (that is, the root directory of your website), put the THINKPHP core folder into the test root directory, and create a new file index.php in the test root directory, and add the following code:

// 定义ThinkPHP框架路径
define('THINK_PATH', './Thinkphp');
//定义项目名称和路径。这2句是重点。
define('APP_NAME', 'test');
define('APP_PATH', './test');
// 加载框架入口文件
require(THINK_PATH."/ThinkPHP.php");
//实例化一个网站应用实例
$App = new App();
//应用程序初始化
$App->run();

Run "http://localhost/test/index.php". You will see the ThinkPHP welcome page. Open your test directory again and find that there is an additional test folder in the root directory. At this time, your project directory has been generated.
Open the /test/test/conf/ directory, create a new "config.php", and configure your database connection.

<?php
return array(
&#39;DB_TYPE&#39;=>&#39;mysql&#39;,
&#39;DB_HOST&#39;=>&#39;localhost&#39;,
&#39;DB_NAME&#39;=>&#39;test&#39;, //新建的数据库名test
&#39;DB_USER&#39;=>&#39;root&#39;, //数据库用户名
&#39;DB_PWD&#39;=>&#39;&#39;, //数据库密码
&#39;DB_PORT&#39;=>&#39;3306&#39;,
);
?>

If you want to turn on debug mode, please add

"debug_mode"=>true

to the array 3. Implementation of basic page input and output.
(1) Open /test/test/lib/action/IndexAction.class.php, you will find the following code

<?php
// 本类由系统自动生成,仅供测试用途
class IndexAction extends Action{
public function index(){
header("Content-Type:text/html; charset=utf-8");
echo "<p style=&#39;font-weight:normal;color:blue;float:left;width:345px;text-align:center;border:1px solid silver;background:#E8EFFF;padding:8px;font-size:14px;font-family:Tahoma&#39;>^_^ Hello,欢迎使用<span style=&#39;font-weight:bold;color:red&#39;>ThinkPHP</span></p>";
}
}
?>

is automatically generated by the system The index() function in the indexaction class is the default home page call function. You can use http://localhost/test/index.php or http://localhost/test/index.php/index to access it

(2) We will ignore it for now. First we need a form submission page. Open "/test/test/tpl/default/index/", create a new file add.html.

<form method="post" action="__URL__/insert">
<p>姓名:<input name="name" type="text" ></p>
<p>内容:<input name="content" type="text"></p>
<p>提交:<input type="submit" value="submit"></p>
</form>

After saving, enter http://localhost /test/index.php/index/add, you will be able to see the page you added. Among them, __URL__ (url should be capitalized) is converted to the corresponding address /test/index.php/Index/.
Here is a brief introduction to the relationship between templates and actions. For each action, the corresponding template is an html file with the same name. For example, index() under the index class corresponds to default/index/index.html, and add.html obviously corresponds to add() under the index class.
We can even access add in the form of accessing add() (http://localhost/test/index.php/index/add) when there is only add.html and no corresponding add() action. html template. Placeholders under the add.html template will be replaced with corresponding data. The effect is as follows.

(3) It can be seen from the "action=__URL__/insert" of the form that the action for form processing is /test/index.php/index/insert, so we have to add the insert action to process it. Form submission data. Before that, we still have one important thing to do, which is to add a new model file. Through the creation of the model file, we will be able to use convenient methods to operate the database in the insert action.
Open the /test/test/lib/model/ folder and create a new file TestModel.class.php. Open it, enter and Save the following code

<?php
class TestModel extends Model {
}
?>

Simply put, this is the basic file for ActiveRecord implementation. The naming rule is to add Model after the table in your database. For example, the table we are going to use is test, my file name must be TestModel.class.php, and the class name under the file must be TestModel.

Next, we return to the indexaction.class.php file, delete the original code, and add the following code.

class IndexAction extends Action{
//表单数据添加到数据库
public function insert() {
//实例化我们刚才新建的testmodel.
$test = D(&#39;Test&#39;);
if ($test->create()) {
//保存表单数据就这一步。thinkphp已经全部做完了。
$test->add();
$this->redirect();
}else{
exit($test->getError()。&#39;[ <A HREF="javascript:history.back()">返 回</A> ]&#39;);
}
}
}

(4) Next, we need to add a homepage default display action index() to the IndexAction class to call the form data.

public function index() {
//依旧是实例化我们新建的对应相应表名的model.这是我们进行快捷表操作的重要关键。
$test = D(&#39;Test&#39;);
//熟悉这段代码么?计算所有的行数
$count = $test->count(&#39;&#39;,&#39;id&#39;);
//每页显示的行数
$listRows = &#39;3&#39;;
//需要查询哪些字段
$fields = &#39;id,name,content&#39;;
//导入分页类 /ThinkPHP/lib/ORG/Util/Page.class.php
import("ORG.Util.Page");
//通过类的构造函数来改变page的参数。$count为总数,$listrows为每一页的显示条目。
$p = new Page($count,$listRows);
//设置查询参数。具体见“ThinkPHP/Lib/Think/Core/Model.class.php”1731行。
$list = $test->findall(&#39;&#39;,$fields,&#39;id desc&#39;,$p->firstRow.&#39;,&#39;.$p->listRows);
//分页类做好了。
$page = $p->show();
//模板输出
$this->assign(&#39;list&#39;,$list);
$this->assign(&#39;page&#39;,$page);
$this->display();
}

It’s time to set up a template. Create a new index.html under /test/test/tpl/default/index/ (because it corresponds to index() by default. Therefore, you can directly assign in the program without specifying the template file. Of course, this can be configured.)

<hr><a href="__URL__/add">填写</a>
//分页显示,这一行
<hr>{$page}<hr>
//数据显示。下面的参数很快会再进行详解。它很好理解。
<volist name="list" id="vo">
<p>姓名:{$vo.name}</p>
<p>内容:{$vo.content}</p>
<hr>
</volist>

Save him. Then enter http://localhost/test/
Congratulations. You have learned how to use thinkphp to create pagination

The above is the entire content of this article. I hope it will be helpful to everyone's learning. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

PHP backend method to implement paging subscript generation code for web pages

About thinkPHP3.2 implementation How to customize paging styles

Analysis on adding js event paging class customPage.class.php to thinkPHP framework

The above is the detailed content of ThinkPHP data paging. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),