例如,我在 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 时,查询是否仍会被执行,否则它将被忽略?
答案 0 :(得分:3)
是,查询仍将执行,因为您首先加载PHP文件。一旦执行了查询,您的PHP文件将加载模板,无论您是否放置{$news}
数据库查询都将执行。
如果您不需要运行查询,可以添加一个标志(例如):
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}