smarty使用变量+mysqli+数组+运算+实例

来源:互联网 发布:yum openssl安装 编辑:程序博客网 时间:2024/05/22 11:55

回顾:

1、        压缩包----解压---libs

2、        php文件中步骤

1)        引用模板类文件smarty.class.php

2)        创建模板对象$tpl

3)        分配变量assign 介绍

4)        选择模板文件display

Html文件---变量为主

 

新内容:

 3、smarty中使用变量

     1)模板中的注释

        模板注释被*号包围,例如 <{* this is a comment *}>

  2)从php文件中分配过来的变量

  连接数据库获取的变量

  经过各种运算得到的结果

  类型:

      标量:string、int、float(double)、boolean

      复合:array、object、null

例如:

  从数据库获取smarty_var_lx,表user获取

连接数据库使用内置类mysqli

不需要include(require),直接用

   php.ini开启extension php_mysqli.dll

   重启apache

 

配置文件init.inc.php中:

   include(“./libs/Smarty.calss.php”);

   $tpl=new Smarty();

   $tpl->template_dir=’./templates’;

   $tpl->compile_dir=”./templates_c”

   $tpl->left_delimiter=”<{”;

   $tpl->right_delimiter=”}>”;

 

b.php中:

  第一步:连接数据库

 $mysqli=new mysqli(“localhost”,”root”,”123”,”smarty_var_lx”);

 

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

$row=$result->fetch_assoc();

$tpl->assign(“id”,$row[‘id’]);

$tpl->assign(“name”,$row[‘name’]);

$tpl->assign(“age”,$row[‘age’]);

$tpl->assign(“email”,$row[‘email’]);

$tpl->display(“a.html”);

 

还可以用:fetch_row()

   $mysqli=new mysqli(“localhost”,”root”,”123”,”smarty_var_lx”);

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

   $row=$result->fetch_row();

   $tpl->assign(“row”,$row);

   $tpl->display(“a.html”);

 

a.    html中:

<!—fetch_assoc-->

  <{$id}><br>

  <{$name}><br>

<{$age}><br>

<{email}><br>

 

<!—fetch_row-->

 <{$row[0]}>

<{$row[1]}>

<{$row[2]}>

<{$row[3]}>

 

 

 

 

l      从数据库获取

Smarty3.1.4版本里

关联数组和索引数组一样可以使用[]

  $array1[‘one’]

Smarty2.6.26版本里

关联数组:使用.连接下标;

索引数组:使用[]连接下标;

 

例如:索引数组:b.php:

   $tpl->assign(“array1”,array(“a”,”b”,”c”));

   $tpl->assign(“array2”,array(array(“1”,”2”),array(“3”,”4”)));

a.    html访问:

<{$array1[0]}>

<{$array1[1]}>

<{$array1[2]}>

 

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

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

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

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

 

例如关联数组b.php:

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

  

a.    html访问:

<{$array3.one}>

<{$array3.two}>

 

l      自定义数组

 

例如自定义数组b.php:

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

          $tpl->assign("array5",array("one"=>array("cc"),array("two"=>"dd"),array("three"=>"ee")));

a.html访问:

 <{$array4.one[0]}>

<{$array4[0].two}>

<{$array5.one[0]}>

<{$array5[0].two}>

<{$array5[1].three}>

l      对象

对象名->属性

对象名->方法()

例如b.php:

   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(“zhangsan”,20));

a.html中:

<{$person->name}>

<{$person->age}>

<{$person->say()}>

l     运算

例如b.php:

      $tpl->assign(“num1”,5);

      $tpl->assign(“num2”,10);

a.    html中:

 <{$num1}>

 <{$num2}>

<{$num1+$num2*10}>

 

 

 

 

 

 

原创粉丝点击