標籤:php smarty 模板 if函數 foreach函數
從資料庫查詢資料,瀏覽器以表格形式顯示
模板頁面
<table border="1" width="800" align="center"><caption>使用者資訊表</caption> <{foreach $tdname as $val}> <th><{$val}></th> <{/foreach}> <{foreach $users as $user}> <{if [email protected]}> <tr bgcolor="red"> <{elseif [email protected]}> <tr bgcolor="yellow"> <{elseif [email protected] is even}> <tr bgcolor="pink"> <{else}> <tr bgcolor="gray"> <{/if}> <{foreach $user as $val}> <td align="center"> <{$val}> </td> <{/foreach}> </tr> <{foreachelse}> 沒有使用者查詢出來! <{/foreach}></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);//var_dump($users);$smarty->assign(‘users‘,$users);$query = "desc users";$stmt = $pdo->prepare($query);$smarty->assign("users",$users);$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://s5.51cto.com/wyfs02/M02/86/99/wKioL1fFGAiRzc-5AABWwKiXmGM189.png-wh_500x0-wm_3-wmp_4-s_2544392590.png" title="Firefox_2016-08-30T05-21-49.768Z.png" alt="wKioL1fFGAiRzc-5AABWwKiXmGM189.png-wh_50" />
本文出自 “津沙港灣” 部落格,請務必保留此出處http://11410485.blog.51cto.com/11400485/1844261
PHP Smarty 模板 if函數 foreach函數