首页 > 代码库 > 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循环遍历数据库表后在前台显示