About_Smarty

  Smarty是一个使用PHP写出来的模板PHP模板引擎,是目前业界最著名的PHP模板引擎之一。它分离了逻辑代码和外在的内容,提供了一种易于管理和使用的方法,用来将原本与HTML代码混杂在一起PHP代码逻辑分离。

首先:要导入文件

 1 <?php
 2 include_once('smarty/Smarty.class.php');
 3 
 4 $smarty = new Smarty;
 5 
 6 $smarty->template_dir = './templates/';
 7 $smarty->compile_dir = './templates_c/';
 8 $smarty->config_dir = './configs/';
 9 $smarty->cache_dir = './cache/';
10 
11 $smarty->left_delimiter = "{";
12 
13 $smarty->right_delimiter = "}";
14 
15 ?>

然后:链接数据库

 1 <?php
 2 
 3 //数据库执行的魔术函数
 4 function mysql_magic(){
 5 
 6     //首先我们参数个数是未知的,但是可以通过PHP函数func_get_args
 7     //得到所有的传入参数,返回值是一个数组
 8     //这个函数还有一个相对的方法func_num_args,这个方法是获取传入参数的个数
 9     $argsNum = func_get_args();
10     $args = func_get_args();
11 
12     if($argsNum == 0){
13         echo "没有传入参数,直接返回false";
14         return false;
15     }
16     //array_shift数组方法,会把原数组的第一个位置的元素,移出数组,数组剩下后面的部分,并且将移出的元素返回
17     $sql = array_shift($args);
18     //为了不混淆$args,将args的值复制给另外的数组
19     $values = $args;
20 
21     //使用字符串替换函数str_replace
22     $sql = str_replace("?","'%s'",$sql);
23 
24     //使用vsprintf,将$sql字符串格式化
25     $sql = vsprintf($sql,$values);
26     //数据库执行语句已经拼好了,接下来就是要判断到底是增删改查的哪个语句
27     //根据判断执行不同的操作
28 
29     //取得数据库语句第一个单词
30 //    $s = explode(" ",$sql)[0];
31     $s = substr($sql,0,6);
32 
33     $conn = mysql_connect("localhost","root","") or die("数据连接异常".mysql_error());
34     mysql_select_db("bbs",$conn) or die(mysql_error());
35     mysql_query("set names 'utf8'");
36 
37     $result = mysql_query($sql) or die(mysql_error());
38 
39     if(strcasecmp($s,"insert") == 0){
40         return mysql_insert_id();  //>0->true表示插入成功,返回最新id,=0表示插入失败,没有获取最新插入的id
41     }
42     else if(strcasecmp($s,"update") == 0 || strcasecmp($s,"delete") == 0){
43         return mysql_affected_rows(); //返回几行受影响,>0表示删除或者更新成功,至少都有1行受影响,=0失败,没有行数受影响
44     }
45     else{
46         $arr = array();
47         while($row=mysql_fetch_array($result)){
48             $arr[] = $row;
49         }
50         return $arr;
51     }
52 
53 }
54 
55 ?>

最后:测试

 1 <?php
 2 
 3 include_once("smarty_inc.php");
 4 include("mysql_func.php");
 5 
 6 $sql = "select * from topic where parentid=?";
 7 $topic = mysql_magic($sql,"0");
 8 
 9 $arr = array(
10     array("我是标题1","我是内容1","我是作者1"),
11     array("我是标题2","我是内容2","我是作者2"),
12     array("我是标题3","我是内容3","我是作者3"),
13     array("我是标题4","我是内容4","我是作者4"),
14 );
15 
16 $smarty->assign("name","macio jackson is a good black man");
17 $smarty->assign("age","19");
18 $smarty->assign("address","成都");
19 $smarty->assign("arr",$arr);
20 $smarty->assign("topic",$topic);
21 
22 $smarty->display("index.html");
23 
24 
25 ?>
原文地址:https://www.cnblogs.com/a-moemiss/p/3766615.html