您好,登錄后才能下訂單哦!
從數據庫查詢數據,瀏覽器以表格形式顯示
注意區別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'); ?>
瀏覽器輸出
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。