Ramil
Ramil

Reputation: 91

PHP and Smarty Execution

For example, I have this query in my news.php file:

$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');

However, in my news.tpl file I will not put the {$news} variables. Will the query still be executed when I browse news.php or it will just be ignored?

Upvotes: 2

Views: 574

Answers (1)

Book Of Zeus
Book Of Zeus

Reputation: 49877

Yes, the query will still be executed because you are loading the PHP file first. Once the query is exeucted, your PHP file will load the template whether you put the {$news} or not the database query will be execute.

If you don't need the query to run, you can add a flag (for example):

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

and then in your 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');

and in your .tpl:

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

Upvotes: 3

Related Questions