search
HomeBackend DevelopmentPHP TutorialPHP uses smarty and ADODB to read data in pages_PHP tutorial

PHP uses smarty and ADODB to read data in pages_PHP tutorial

Jul 13, 2016 pm 05:48 PM
basedefinepathphpsmartyPaginationandaccomplishrightdatatry outread

define('BASE_PATH',$_SERVER['DOCUMENT_ROOT']);
define('SMARTY_PATH','smartTestSmarty\');
require BASE_PATH.SMARTY_PATH.'Smarty.class.php';
/*The path of $dir2 is displayed on the performance page and the following strings are the same, causing smarty to not be able to find the templates path*/
//$dir2 = "../Smarty/templates/";
class SmartyProject extends Smarty{
       
Function SmartyProject(){
/*You must add this parent::__construct();, otherwise, Smarty will not be constructed, truncate, etc. cannot be used,
* This doesn’t seem to make sense, but in fact,
* This does solve the problem that truncate cannot be used*/
        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){//Constructor
          $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';//Reference the main file of 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));//Remove the first 6 characters of the sql statement
$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'){
//This does not return a result set, or returns an empty set
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;
//Execute query statement
$this->rs = $this->conn->PageExecute($this->sqlstr,$this->pagesize,$this->nowpage);//Call this method in the ADODO class
@$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); //Execute query statement
           $record = count($allrs->GetRows());//Total number of statistical records
         $pagecount = ceil($record/$this->pagesize);//Calculate how many pages there are
@$str.="Total ".$contentname." ".$record." ".$utits." Each page displays ".$this->pagesize.
".$utits." ".$this->rs->AbsolutePage()." Pages/Total ".$pagecount." Pages";
                                                                                                                                                                                                   $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();//实例化分页类 

This file is an instantiation of the class in the above file. It can be named smartyDaoImpl.php, or named as you like. The function is very simple, right?
The next thing to do is to create a test case to test the paging code. Of course, this test also contains two files, one is the controller and the other is the view. The code of the controller is:

include_once 'conn/smartyDaoImpl.php';
$arr_page = $seppage->ShowData("select * from localinfo", $conn, 5, $_GET['page']);//Execute paging query
if(!$arr_page)
$smarty->assign('page',"F");
else {
$smarty->assign('page','T');
$smarty->assign('showpage',$seppage->ShowPage("record", "a", "", "", "a1"));//Assignment paging template
$smarty->assign('arr_page',$arr_page);//Copy the query record to the template
}
$smarty->display('view/fenyeShow.html');//Specify the template for displaying data
Give it a name, let’s call it smarty_ADODB_fenye.php. As you can see, we used it at the beginning:

include_once 'conn/smartyDaoImpl.php';
Here, please explain that the previous two files are placed in the conn folder, and the test cases are written in the same level directory as conn
Then view file, don’t put the view file in the wrong place. See this statement in the first class we wrote

$this->template_dir = BASE_PATH.SMARTY_PATH.'/templates/';
The absolute path to the view file is specified here, because,

$smarty->display('view/fenyeShow.html');//Specify the template for displaying data
This statement,

$smarty->display('view/fenyeShow.html');//Specify the template for displaying data
So, we are going to

BASE_PATH.SMARTY_PATH.'/templates/
Create a folder named view under the path, and then create a file named fenyeShow.html. Of course, you can choose a name you like, but you must ensure the consistency specified in the program
The content in the view template is as follows:





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}


Okay, it’s done. Just locate the smarty_ADODB_fenye.php file in the browser, start the server, OK, and you will see the paging effect.
In the process of doing it, I also encountered some problems. One is that I cannot try the truncate statement. This problem is very strange. I checked it on the smarty official website and found that when the smarty subclass is instantiated, its parent class Smarty will not be instantiated. , therefore, will cause truncate to be unavailable. The solution is naturally to call the parent class constructor in the subclass.

Excerpted from 0+0+0+...=1

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478454.htmlTechArticle?php define(BASE_PATH,$_SERVER[DOCUMENT_ROOT]); define(SMARTY_PATH,smartTestSmarty\); require BASE_PATH. SMARTY_PATH.Smarty.class.php; /*The path of $dir2 displayed to the performance page is this...
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft