Home php教程 php手册 php试用smarty和ADODB实现对数据分页读取

php试用smarty和ADODB实现对数据分页读取

Jun 13, 2016 am 10:46 AM
base define path php smarty Pagination and accomplish right data try out read

define('BASE_PATH',$_SERVER['DOCUMENT_ROOT']); 
define('SMARTY_PATH','\smartTest\Smarty\\'); 
require BASE_PATH.SMARTY_PATH.'Smarty.class.php'; 
/*$dir2的这种路径显示到表现页是这下面字符串是一样,导致smarty找不到templates路径*/ 
//$dir2 = "../Smarty/tempplates/"; 
class SmartyProject extends Smarty{ 
     
    function SmartyProject(){ 
        /*必须加这个parent::__construct();,否则,Smarty不会被构造,truncate等不能用,
         * 但这似乎没有道理,但事实上,
         * 这么做确实解决了truncate不能使用的问题*/ 
        parent::__construct(); 
        $this->template_dir = BASE_PATH.SMARTY_PATH.'/templates/'; 
        $this->compile_dir = BASE_PATH.SMARTY_PATH.'/templates_c/'; 
        $this->config_dir = BASE_PATH.SMARTY_PATH.'/configs/'; 
        $this->cache_dir = BASE_PATH.SMARTY_PATH.'/cache/'; 
    } 

 
class ConnDB{ 
    var $dbtype; 
    var $host; 
    var $user; 
    var $pwd; 
    var $dbname; 
    var $debug; 
    var $conn; 
    function ConnDB($dbtype, $host, $user, $pwd, $dbname, $debug=FALSE){//构造函数 
        $this->dbtype=$dbtype; 
        $this->host=$host; 
        $this->user=$user; 
        $this->pwd=$pwd; 
        $this->dbname=$dbname; 
        $this->debug=$debug;  
    } 
    function GetConnId(){ 
        require BASE_PATH.'/smartTest/adodb5/adodb.inc.php';//将adodb的主文件引用进来 
        if($this->dbtype == 'mysql'){ 
            $this->conn = NewADOConnection('mysql'); 
            $this->conn->Connect($this->host, $this->user, $this->pwd, $this->dbname); 
        }else if($this->dbtype == 'mssql'){ 
            $this->conn = NewADOConnection('mssql'); 
            $this->conn->Connect($this->host, $this->user, $this->pwd, $this->dbname); 
        }else if($this->dbtype == 'access'){ 
            $this->conn = NewADOConnection('access'); 
            $this->conn->Connect("Driver={Microsoft Access Driver(*.mdb)};Dbq=".$this->dbname.";Uid=".$this->user.";Pwd=".$this->pwd.";"); 
        } 
        $this->conn->Execute("set names utf-8"); 
        if($this->dbtype == 'mysql') 
            $this->conn->debug = $this->debug; 
        return $this->conn; 
    } 
    function CloseConnId(){ 
        $this->conn->Disconnect(); 
    } 

 
class AdminDB{ 
    function ExecSQL($sqlstr, $conn){ 
        $sqltype = strtolower(substr(trim($sqlstr), 0,6));//去sql语句的前6个字符 
        $rs = $conn->Execute($sqlstr); 
        if($sqltype == 'select'){ 
            $array = $rs->GetRows(); 
            if(count($array)==0 || $rs == false) 
                return false; 
            else  
                return $array; 
        }else if($sqltype == 'update'||$sqltype == 'insert'||$sqltype == 'delete'){ 
            //这写都是不返回结果集的,或者说返回空集合 
            if($rs) 
                return true; 
            else  
                return false; 
        } 
    } 

class SepPage{ 
    var $rs; 
    var $pagesize; 
    var $nowpage; 
    var $array; 
    var $conn; 
    var $sqlstr; 
    function ShowData($sqlstr,$conn,$pagesize,$nowpage){ 
        if(!isset($nowpage)||$nowpage==""){ 
            $this->nowpage = 1; 
        }else{ 
            $this->nowpage = $nowpage; 
        } 
        $this->pagesize = $pagesize; 
        $this->conn = $conn; 
        $this->sqlstr = $sqlstr; 
        //执行查询语句 
        $this->rs = $this->conn->PageExecute($this->sqlstr,$this->pagesize,$this->nowpage);//调用ADODO类中的这个方法 
        @$this->array = $this->rs->GetRows(); 
        if(count($this->array)==0||$this->rs == false) 
            return  false; 
        else  
            return  $this->array; 
    } 
    function ShowPage($contentname, $utits, $anotherserchstr, $anotherserchstrs, $class){ 
        $allrs = $this->conn->Execute($this->sqlstr); //执行查询语句 
        $record = count($allrs->GetRows());//统计记录总数 
        $pagecount = ceil($record/$this->pagesize);//计算共有多少页 
        @$str.="共有".$contentname." ".$record." ".$utits." 每页显示 ".$this->pagesize. 
        " ".$utits." 第 ".$this->rs->AbsolutePage()." 页/共 ".$pagecount." 页"; 
        $str.="    "; 
        if(!$this->rs->AtFirstPage()) 
            $str.="             $anotherserchstrs."class=".$class.">首页"; 
        else  
            $str.="首页"; 
        $str.=" "; 
        if (!$this->rs->AtFirstPage()) 
            $str.="rs->AbsolutePage()-1)."¶meter1=".$anotherserchstr."¶meter2=". 
            $anotherserchstrs."class=".$class.">上一页
"; 
        else 
            $str.="上一页"; 
        $str.=" "; 
        if(!$this->rs->AtLastPage()) 
            $str.="rs->AbsolutePage()+1)."¶meter1=".$anotherserchstr."¶meter2=". 
            $anotherserchstrs."class=".$class.">下一页
";   
        else 
            $str.="下一页"; 
        $str.=" "; 
        if(!$this->rs->AtLastPage()) 
            $str.="             $anotherserchstrs."class=".$class.">尾页"; 
        else 
            $str.="尾页"; 
        if(count($this->array)== 0||$this->rs==false) 
            return ""; 
        else 
            return $str; 
    } 

以上代码定义了几个类,用来实现数据库的连接啊,操作数据库,分页实现,数据库的存储,以及一个smarty类的子类,其实这个子类也没有实现什么特别的功能。将其命名为
smartyDAO.php或这随便取个什么名字都可以,当然,还有一点要注意的是,我里面试用了require语句,对于这些路径,大家都要该到自己对应的目录去。

require 'smartyDao.php'; 
//数据库类实例 
$conobj  = new ConnDB("mysql", "localhost", "root", "brave", "bank"); 
$conn = $conobj->GetConnId(); 
//数据库操作类对象 
$admindb = new AdminDB(); 
//Smarty模板配置类对象 
$smarty = new SmartyProject(); 
 
$seppage = new SepPage();//实例化分页类 

这个文件就是对上面那个文件中类的实例化,可以命名为 smartyDaoImpl.php,或者命名为你自己喜欢的名字,作用很简单,是吧
然后要做的工作就是随便建立一个测试用例,来测试分页代码了,当然,这个测试也包含两个文件,一个是控制器,另外一个视图,控制器的代码是:

include_once 'conn/smartyDaoImpl.php'; 
$arr_page = $seppage->ShowData("select * from localinfo", $conn, 5, $_GET['page']);//执行分页查询 
if(!$arr_page) 
    $smarty->assign('page',"F"); 
else { 
    $smarty->assign('page','T'); 
    $smarty->assign('showpage',$seppage->ShowPage("记录", "个", "", "", "a1"));//赋值分页模版 
    $smarty->assign('arr_page',$arr_page);//将查询记录复制给模版 

$smarty->display('view/fenyeShow.html');//指定显示数据的模版 
取个名吧,就叫做smarty_ADODB_fenye.php吧。可以看到,我们在开头用到了:

include_once 'conn/smartyDaoImpl.php'; 
这里,说明一下,前面那两个文件都是放在conn文件夹下的,测试用例写在conn同级目录下
然后视图文件,视图文件放的地方可别放错了看到我们写的第一个类中有这样一条语句

$this->template_dir = BASE_PATH.SMARTY_PATH.'/templates/'; 
这里就是指定了视图文件的绝对路径,因为,

$smarty->display('view/fenyeShow.html');//指定显示数据的模版 
这条语句,

$smarty->display('view/fenyeShow.html');//指定显示数据的模版 
所以,我们要在

BASE_PATH.SMARTY_PATH.'/templates/ 
路径下建立一个文件夹名为view,然后在先建一个文件名为fenyeShow.html,当然你可以取你喜欢的名字,但是要保证程序中指定的一致性
视图模版里面的内容是以下:

 
 

 
 
Insert title here 
 
 
 
{section name=id loop=$arr_page} 
 
 
 
 
 
 
 
{/section} 
 
 
 
 
{$arr_page[id].Id} {$arr_page[id].temperature} {$arr_page[id].illumination} {$arr_page[id].moisture} {$arr_page[id].times|truncate:5:"..."}
{$showpage}
 
 
 

好了,做完了,只要在浏览器中定位到smarty_ADODB_fenye.php这个文件,启动服务器,OK,将会看到分页效果了。
我在做的过程中,也遇到了一些问题,一个是不能试用 truncate语句,这个问题很奇怪,到smarty官网查了下,让来,smarty子类实例化时,不会实例化其父类Smarty,因此,会导致truncate不可以用,解决的办法,自然是在子类中调用父类构造方法。

摘自 0+0+0+...=1

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles