標籤:php smarty 模板 section函數 輸出表格
從資料庫查詢資料,瀏覽器以表格形式顯示
注意區別index 和iteration
index為數組下標索引
iteration為序號
模板頁面
<table border="1" width="800" align="center"><caption>使用者資訊表</caption> <th align="center">index</th> <th align="center">iteration</th> <{foreach $tdname as $val}> <th align="center"><{$val}></th> <{/foreach}> <{section name="one" loop=$users step=2 start=2}> <{if $smarty.section.one.first}> <tr bgcolor="red" align="center"> <{elseif $smarty.section.one.last}> <tr bgcolor="yellow" align="center"> <{elseif $smarty.section.one.iteration is even}> <tr bgcolor="pink" align="center"> <{else}> <tr bgcolor="green" align="center"> <{/if}> <td><{$smarty.section.one.index}></td> <td><{$smarty.section.one.iteration}></td> <td><{$users[one].id}></td> <td><{$users[one].username}></td> <td><{$users[one].password}></td> <td><{$users[one].email}></td> </tr> <{sectionelse}> 沒有使用者查詢出來! <{/section}></table>
php頁面
<?php //建立smarty對象require_once ‘./libs/Smarty.class.php‘;//定義根目錄define(‘ROOT‘, str_replace("\\", "/",dirname(__FILE__))."/");//執行個體化Smarty類$smarty=new Smarty();//設定定界符$smarty->left_delimiter="<{";$smarty->right_delimiter="}>";//設定為false 定界符號左右可以有空格$smarty->auto_literal = false;//添加一個外掛程式的目錄//$smarty->setPluginsDir(ROOT."/libs/myplugins/");//注意添加一個外掛程式,要把系統預設設定的路徑加入 否則不能使用預設系統的外掛程式$smarty->setPluginsDir(array( ROOT."/libs/plugins/",//系統預設設定的路徑 ROOT."/libs/myplugins/",//自訂的));//串連資料庫const DSN = ‘mysql:host=localhost;dbname=test‘;const DBUSER = ‘root‘;const DBPWD = ‘root‘;try{ $pdo = new PDO(DSN, DBUSER,DBPWD);}catch(PDOException $e){ echo "資料庫連接失敗:".$e->getMessage(); exit;}$query = "select id, username, password,email from users";$stmt = $pdo->prepare($query);$stmt ->execute();$users = $stmt->fetchAll(PDO::FETCH_ASSOC);$smarty->assign(‘users‘,$users);//var_dump($users);$query = "desc users";$stmt = $pdo->prepare($query);$stmt ->execute();$tdname = $stmt->fetchAll(PDO::FETCH_COLUMN);//var_dump($tdname);$smarty->assign(‘tdname‘,$tdname);//變數輸出$smarty->display(‘hello.tpl‘);?>
瀏覽器輸出
650) this.width=650;" src="http://s4.51cto.com/wyfs02/M02/86/9B/wKioL1fFJxKALG6BAAAyQVP1Cy4471.png-wh_500x0-wm_3-wmp_4-s_909034851.png" title="Firefox_2016-08-30T06-18-03.986Z.png" alt="wKioL1fFJxKALG6BAAAyQVP1Cy4471.png-wh_50" />
本文出自 “津沙港灣” 部落格,請務必保留此出處http://11410485.blog.51cto.com/11400485/1844299
PHP Smarty 模板 section函數 輸出表格