例如,我的 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/