Smarty实现的代码(二)

来源:互联网 发布:淘宝拖鞋棉 编辑:程序博客网 时间:2024/06/14 18:36
 

b.php文件

<?php

include("./init.inc.php");

$a=10;

$tpl->assign("title","this is php various");

$tpl->assign("title1","$a");

$tpl->assign("title2","true");

 

 

//从数据库lianxi,表user获取

//连接数据库使用内置类mysqli

//不需要include(require)。直接用

//php.ini开启extension=php_mysqli.dll,重启apace

//mysqli类:连接

//第一步:连接数据库

 

$mysqli = new mysqli("localhost","root","","smarty_var");

//结果集对象,创建该对象不能newmysqli_result,而是通过调用mysqli的query方法直接返回结果集对象

 

 $result = $mysqli->query("select * from user");

 

//第三步:使用该对象获取结果集中的(关联、索引)数组

 

//索引数组分配

$row = $result->fetch_row();

print_r($row);

 

//所以数组可以一次性分配

$tpl->assign("row",$row);

//自定义数组

$tpl->assign("array1",array("1","2","3"));//一维索引数组

$tpl->assign("array2",array(array("a","b"),array("c","d")));

 

//关联数组

$tpl->assign("array3",array("one"=>"one","two"=>"two"));

 

 

$tpl->assign("array4",array("one"=>array("aa"),array("two"=>"bb")));

//对象的分配

class Person{

 var $name;

 var $age;

 public function __construct($name,$age){

   $this->name = $name;

   $this->age = $age;

   }

function say(){

return $this->name."的年龄是".$this->age;

 

}

}

//分配变量

 

$tpl->assign("person",new Person("as",20));

 

//运算

$tpl->assign("$num1",10);

$tpl->assign("$num2",10);

 

 

$tpl->display("a.html");

?>

a.html文件

模版文件中的变量分类<br>

一、由php中分配过来的变量<br>

<br>

<{ * 这是smarty的注释信息 *}>

<!--这是html注释-->

<br>

这是从php分配过来的标量类型的变量<br>

<{$title}>

<br>

<{$title1}>

<br>

<{$title2}>

 

 

<br>

从数据库获取变量<br>

 

<!--<br><br><br><br><br>

<{$name}><br>

<{$username}><br>

<{$pass}><br>

 

<{*$result['id']*}><br>-->

<{$row[0]}><br>

<{$row[1]}><br>

<{$row[2]}><br>

<br><br>

 

<{$array1[0]}><br>

<{$array1[1]}><br>

<{$array1[2]}><br>

 

<br>

 

<{$array2[0][0]}><br>

<{$array2[0][1]}><br>

<{$array2[1][0]}><br>

<{$array2[1][1]}><br>

 <br><br><br><br><br>

 <{$array3.one}><br>

 <{$array3.two}><br>

 

 <br><br>

 <{$array4.one[0]}><br>

 <{$array4[0].two}><br>

 

 

 <br><br>

<{$person->say()}><br>

<{$person->name}><br>

<{$person->age}><br>

<br><br>

 

<{$num1}><br>

<{$num2}><br>

原创粉丝点击