Search code examples
phpsmarty

Smarty passing data from controller to view and displaying data


I'm getting data from database with this function which is working fine.

static function dohvatiSveOlijeku($id){
    $baza = new Baza();

    $upit = "SELECT * FROM lijek WHERE status = 1 and lijek.id = " . $id;

    $rez = $baza->selectDB($upit);
    if($rez->num_rows == 0){
        return null;
    }else{
        $red = $rez->fetch_assoc();
        return $red;
    }
}

and this is my controller which is using parameter id to get data from model...

if (isset($_GET['id'])) {
$LijekSve = Lijek::dohvatiSveOlijeku($_GET['id']);
}


$Smarty->assign('lijek', $LijekSve);
$Smarty->display('view/lijek.tpl');

and this is a view which is presenting given data

{foreach from=$lijek item =lijekpodaci}
    <div>
        <p>{$lijekpodaci.cijena} kuna</p>
    </div>
{/foreach}

For each item in table I get this error

 Illegal string offset 'cijena' in C:\xampp\htdocs\ljekarna\smarty\libs\sysplugins\smarty_internal_templatebase.php(171) : eval()'d code on line 69 1 kuna

I also tried this, but the same error shows

{$lijekpodaci['cijena']}

Solution

  • Why not try using a conditional statement to check if the $lijek Array is empty before you loop? Here's how:

        <?php
            // INITIALIZE $LijekSve TO AN EMPTY ARRAY JUST IN CASE $_GET['id'] ISN'T SET
            $LijekSve       = array();      
            if (isset($_GET['id'])) {
                $LijekSve   = Lijek::dohvatiSveOlijeku($_GET['id']);
            }
    
            $Smarty->assign('lijek', $LijekSve);
            $Smarty->display('view/lijek.tpl');
        ?>
    

    TEMPLATE

            {if !empty($lijek) }
                {foreach from=$lijek item =lijekpodaci}
                    <div>
                        <p>{$lijekpodaci.cijena} kuna</p>
                    </div>
                {/foreach}
            {/if}