Search code examples
phphtml-selectsmarty

Option list in Smarty


enter image description hereBy using Smarty Template Engine I got confused, I wanted to retrieve records from database and put them into an option list.

That was simple in PHP

$sqlFrom = "SELECT * FROM howto_lang_From WHERE Activation=1";
$resultFrom = mysql_query($sqlFrom);

echo    '<select name="from" class="list" required>';
echo    '<option value="">Choose</option>';

while ($lanFrom = mysql_fetch_assoc($resultFrom)) {

      echo      "<option>$lanFrom[From]</option>";      
        }

echo    '</select>';

but in Smarty template I am not sure, tried something like this, but couldn't get it to work

**PHP:**
$sqlFrom = "SELECT * FROM howto_lang_From WHERE Activation=1";
$resultFrom = mysql_query($sqlFrom);

while ($lanfrom = mysql_fetch_assoc($resultFrom)) {
$result[] = $lanfrom;


}

$smarty->assign("FROM", "$result");

**Template:**
    <select name="from" class="list" required>
    <option value="">Choose</option>
{section name=from loop=$FROM}
        <option>{$FROM[from].From}</option>     
{/section}  
        </select>

and one more question!! I am an average PHP programmer, after a glance on this template engine, I faced lots of confusion!! SO, DOES IT REALLY WORTH TO CREATE SITES DEPENDING ON SMARTY? is not the original way of combining PHP and HTML much easier and readable!?

Thanks.


Solution

  • There is only one problem with your code. You would knew about it if you had error_reporting set to E_ALL.

    Using this line:

    $smarty->assign("FROM", "$result");
    

    You make that your $result array is being converted to string and if error_reporting is set properly you will get notice: Notice: Array to string conversion in ...

    So it's enough to change this line into:

    $smarty->assign("FROM", $result);
    

    simply removing quotes.

    You should also use PDO or mysqli as mysql is deprecated.

    Is it worth to use templates? In my opinion - yes. They make you to separate logic from displaying data. You first get data and prepare them for displaying and than display it. Of course you can also do it in pure PHP but Smarty syntax (or other templates syntax) makes view to be easier skimmed or changed. However you need to learn template syntax, settings and so on and it's usually not so obvious.