温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP Smarty 模板 section函数 输出表格

发布时间:2020-07-14 19:11:48 来源:网络 阅读:698 作者:津沙港湾 栏目:web开发

从数据库查询数据,浏览器以表格形式显示

注意区别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');

?>

浏览器输出

PHP Smarty 模板  section函数  输出表格


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI