首页 > 代码库 > smarty循环遍历数据库表后在前台显示
smarty循环遍历数据库表后在前台显示
1,smarty使用PDO方式循环遍历
<?php //初始化 require ‘../libs/Smarty.class.php‘; // require ‘chuan.php‘; $smarty = new Smarty; //配置 // $smarty->debugging = true; $smarty->caching = false; $smarty->force_compile=true; //基本操作 function cc(){ try{ $dbh = new PDO(‘mysql:host=localhost;dbname=sm‘, ‘root‘, ‘‘); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->exec(‘set names utf8‘); /*查询*/ $stmt = $dbh->prepare(‘SELECT * FROM user‘); $stmt->execute(); $arr = array(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $arr[]=$row ; } return $arr; // 现在运行完成,在此关闭连接 $dbh = null; }catch(PDOException$e){ print"Error!:".$e->getMessage()."<br/>"; die(); } } $smarty->assign(‘ids‘,cc()); //显示设置 $smarty->display(‘user.tpl‘);
2,前台显示
{config_load file="test.conf" section="setup"} {include file="header.tpl" title=foo} <table border="1" cellspacing="0" cellpadding="0"> <th>姓名</th> <th>地址</th> {foreach $ids as $color} <tr align="center"> <td>{$color.name}</td> <td>{$color.info}</td> </tr> {/foreach} </table> {include file="footer.tpl"}
总结:这种操作方式摈弃了原始PHP把数据库连接放到页面去操作,类似JAVA的操作方式,在后台遍历数据库,把结果集RS放置在一个数组ARR里面,然后把ARR返还给方法,把方法赋予一个变量,前台进行循环取值;
这个JAVA很相似;
smarty循环遍历数据库表后在前台显示
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。