PHP 和 Smarty 执行

标签 php smarty

例如,我的 news.php 文件中有此查询:

$sql = 'SELECT * FROM `news` ORDER BY `id` DESC LIMIT 0, 5'; 
$result = mysql_query($sql) or die("Query failed : " . mysql_error());
while ($line = mysql_fetch_assoc($result)) {
    $value[] = $line;
}
// Assign this array to smarty...
$smarty->assign('news', $value);
 // Display the news page through the news template
$smarty->display('news.tpl');

但是,在我的 news.tpl 文件中,我不会放置 {$news} 变量。当我浏览 news.php 时,查询仍然会执行还是会被忽略?

最佳答案

,查询仍将执行,因为您首先加载 PHP 文件。执行查询后,无论您是否放置 {$news} ,您的 PHP 文件都会加载模板,数据库查询将被执行。

如果不需要运行查询,可以添加一个标志(例如):

http://www.domain.com/news.php?show=0

然后在你的 PHP 中:

$value = array(); // this way if the variable is not used, you create a empty array.

if(isset($_GET['show']) && $_GET['show'] == 1) {
    $sql = 'SELECT * FROM test.`name` ORDER BY 1 DESC LIMIT 0, 5';
    $result = mysql_query($sql) or die("Query failed : " . mysql_error());
    while ($line = mysql_fetch_assoc($result)) {
        $value[] = $line;
    }
}
// Assign this array to smarty...
$Smarty->assign('news', $value);

// Display the news page through the news template
$Smarty->display('news.tpl');

在你的.tpl中:

{section name=loopname loop=$news}
  // your news code
{sectionelse}
  No news today!
{/section}
{$news}

关于PHP 和 Smarty 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8426061/

相关文章:

php - <body> 标签 & script 标签和 link 标签下方的空白区域位于 head 标签的 body 标签下方

php - Jinja2 与 Smarty

php - 从 PHP API 创建 REST API

php - 设置 cakephp 的默认值

Php 视频播放百分比

php - 根据上一行的日期获取下一行的内容

smarty - 一个括号中存在两个或多个不平等条件?

php - 将 select_query 更改为 mysql_query?

javascript - 如何使用 ezMark 生成的复选框?

php - 使用 numberFormatter 格式化货币