PHP Smarty 模板 if函数 foreach函数
从数据库查询数据,浏览器以表格形式显示
模板页面
<tableborder="1"width="800"align="center"><caption>用户信息表</caption><{foreach$tdnameas$val}><th><{$val}></th><{/foreach}><{foreach$usersas$user}><{if$user@first}><trbgcolor="red"><{elseif$user@last}><trbgcolor="yellow"><{elseif$user@indexiseven}><trbgcolor="pink"><{else}><trbgcolor="gray"><{/if}><{foreach$useras$val}><tdalign="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=newSmarty();//设定定界符$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/",//自定义的));//连接数据库constDSN='mysql:host=localhost;dbname=test';constDBUSER='root';constDBPWD='root';try{$pdo=newPDO(DSN,DBUSER,DBPWD);}catch(PDOException$e){echo"数据库连接失败:".$e->getMessage();exit;}$query="selectid,username,password,emailfromusers";$stmt=$pdo->prepare($query);$stmt->execute();$users=$stmt->fetchAll(PDO::FETCH_ASSOC);//var_dump($users);$smarty->assign('users',$users);$query="descusers";$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');?>
浏览器显示
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。