2011-12-08 30 views
2

例如,我有这个疑问在我news.php文件:PHP和Smarty的执行

$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.php时,查询是否仍然会执行,否则它会被忽略?

回答

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}