Search code examples
phptemplate-engine

Mysql result loop for template engine


What I am trying to do is to loop all the results with a use of very simple template engine. The problem is that the script executes same result many times.. Right now there is 3 test works in the database(Test_1,Test_2,Test_3), so basically the result looks like this now:

Test_3 Test localhost

Test_3 Test localhost

Test_3 Test localhost

$result = $pDatabase->query($query) or die('Query failed: ' . mysql_error());
    while ($row = mysql_fetch_array($result)) {
        //Loop Template (row)
        $works_row = new Template("works_row.tpl"); 
            //Changing all from $row[] to {}
            $rows[]=$row;
            $works_row->set("category",$row['category']);
            $works_row->set("name",$row['name']);
            $works_row->set("link",$row['link']);
    }
    foreach ($rows as $row) {
    $works_templates[] = $works_row;
    }
    $works_contents = Template::merge($works_templates);
    mysql_free_result($result);
    //Content part that calls all works
    $works_list  = new Template("works_block.tpl"); 
    $works_list->set("works_rows", $works_contents);

I don't really understand why doesn't it work right


Solution

  • Try this ,it works

        $result = $pDatabase->query($query) or die('Query failed: ' . mysql_error());
        while ($row = mysql_fetch_array($result)) {
            //Loop Template (row)
            $works_row = new Template("works_row.tpl"); 
                //Changing all from $row[] to {}
                $rows[]=$row;
                $works_row->set("category",$row['category']);
                $works_row->set("name",$row['name']);
                $works_row->set("link",$row['link']);
                $works_templates[] = $works_row;
        }
    
        $works_contents = Template::merge($works_templates);
        mysql_free_result($result);
        //Content part that calls all works
        $works_list  = new Template("works_block.tpl"); 
        $works_list->set("works_rows", $works_contents);