2011-12-08 67 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}