I've just started playing with the Smarty template engine and I have trouble believing that you have to loop through you database resultset sticking each row into an array, and then assign the array to a template variable. Just seems like a lot of hoop-jumping (not to mention extra memory consumption) for something that supposed to make your life so wonderfully easy. So somebody please say it ain't so.

I suppose you could use the getAll() method from the Pear database API and that's what I think I'm gonna do unless someone enlightens me.

Thanks.

    I don't unserstand your problem.

    you are reading the DB, fetching an array or object from the result, assign this as reference (not really more memory needed for this) ($smarty->assign_by_ref) to a smarty var and loop through this in your template.

    whats wrong with this? afaik you will have this behaviour with every template class.

      Originally posted by PHPThorsten
      I don't unserstand your problem.

      you are reading the DB, fetching an array or object from the result, assign this as reference (not really more memory needed for this) ($smarty->assign_by_ref) to a smarty var and loop through this in your template.

      I guess I'm dense and need to see a code example. Are you talking about batch-fetching the whole resultset into a data structure and assigning that to the smarty template variable, or are you looping through the results and storing each row in an array which you then assign to a smarty variable?

      I gather the way you handle it in the template is the same in either case.

      PS to EviL_CodE, thanks for the tip, I'll have a look.

        ok, here a little example:

        <?php
        
        /* The Database Connection */
        require 'database.class.php';
        $obj_db = new Database();
        
        /* Smarty Tpl Class */
        require 'smarty.class.php';
        $obj_smarty = new Smarty;
        
        /* SQL Query */
        $str_query_get_whatever = "SELECT field1, field2 FROM table WHERE owner = '1'";
        
        /* Fetching the result to an array */
        $arr_result = $obj_db->query($str_query_get_whatever);
        
        $obj_smarty->assign_by_ref("result", $arr_result);
        
        $obj_smarty->display("template.tpl");
        exit;
        
        ?>
        

        Then you have your Template "template.tpl"

        {include file="header.tpl"}
        
        {section name=resloop loop=$result}
        {$result[resloop].field1} + {$result[resloop].field2} <br>
        {/section}
        
        {include file="footer.tpl"}
        

        BTW: Have a look at http://smarty.php.net/crashcourse.php

        Bye

        Thorsten

          PS:
          Smarty is much faster than a lot of other template system,
          not only because it compiles the templates, you can cache the results and - if the browser has already cached the latest version of the page by itself - you can tell the browser to use his own cache.
          so your server won't need to connect the DB, creates the template and so on everytime a user is requesting your page.

            Originally posted by PHPThorsten

            <?php
            
            /* The Database Connection */
            require 'database.class.php';
            $obj_db = new Database();
            
            // etc
            
            /* Fetching the result to an array */
            $arr_result = $obj_db->query($str_query_get_whatever);
            
            ?>
            

            Is this database.class.php a class of your own devising? The smarty 'section' syntax is for arrays, right? But the return type of (e.g.) mysql_query($sql) isn't array but a 'resource'; the return type of the Pear DB::query($sql) isn't an array but a DB_Result object, which is why when I tried emulating your example it didn't work. So there must still be something I'm not getting. I don't see anything about this in the 'crash course' either.

            Thanks.

              Dear,

              yes, the DB Class I'm calling is written by myself and based ob AdoDB.

              I don't use PEAR DB, so could you please tell me how these Object looks like?

              A print_r() on it woul be very helpful.

              How do you use this object in the moment?

              is every row from the result stored in an extra object or is there an array in this object with the result rows?

                OK, I think I follow now. The database results go into an array; how they get there is your problem. Then you $smarty->assign()and use Smarty's section syntax to iterate/display the array. So I'm basically back where I started.

                Meanwhile I've been looking at the PEAR $db->getAssoc method to see if that would save a step. Anyway you asked for a print_r of the PEAR db resultSet object, so here's my source

                echo "I am {$_SERVER['PHP_SELF']}<br />";
                $smarty = new SmartyDemo;
                
                require_once 'DB.php'; // PEAR database access class
                extract( parse_ini_file("/data/htdocs/sdny/dev/hal.cfg"));
                $dsn = "$driver://$username:$password@$host/$database";
                $db = DB::connect($dsn);
                if (DB::isError($db)) {  die ($db->getMessage()); }
                
                $sql = "select judge_id,lastname, firstname from judges order by lastname limit 5";
                // with the DB::getAssoc() method
                $data = $db->getAssoc($sql);
                if (DB::isError($data)) {  die ($data->getMessage());}
                $result_obj = $db->query($sql);
                print "<pre>Associative array:\n"; 
                print_r($data); 
                
                print "As a PEAR result object:\n";
                print_r($result_obj); 
                print "</pre>";
                $smarty->assign("data",$data);
                $smarty->display('index.tpl');
                ?>
                

                and here's my output.

                
                I am /dev/smarty/demo.php
                
                Associative array:
                Array
                (
                    [3] => Array
                        (
                            [0] => Baer
                            [1] => Harold
                        )
                
                [7] => Array
                    (
                        [0] => Batts
                        [1] => Deborah
                    )
                
                [23] => Array
                    (
                        [0] => Berman
                        [1] => 
                    )
                
                [76] => Array
                    (
                        [0] => Brieant
                        [1] => Charles
                    )
                
                [49] => Array
                    (
                        [0] => Buchwald
                        [1] => Naomi
                    )
                
                )
                As a PEAR result object:
                db_result Object
                (
                    [dbh] => db_mysql Object
                        (
                            [connection] => Resource id #7
                            [phptype] => mysql
                            [dbsyntax] => mysql
                            [prepare_tokens] => Array
                                (
                                )
                
                        [prepare_types] => Array
                            (
                            )
                
                        [num_rows] => Array
                            (
                                [8] => 5
                                [9] => 5
                            )
                
                        [transaction_opcount] => 0
                        [autocommit] => 1
                        [fetchmode] => 1
                        [_db] => interpreters
                        [_debug] => 
                        [_default_error_mode] => 
                        [_default_error_options] => 
                        [_default_error_handler] => 
                        [_error_class] => DB_Error
                        [_expected_errors] => Array
                            (
                            )
                
                        [features] => Array
                            (
                                [prepare] => 
                                [pconnect] => 1
                                [transactions] => 1
                                [limit] => alter
                            )
                
                        [errorcode_map] => Array
                            (
                                [1004] => -15
                                [1005] => -15
                                [1006] => -15
                                [1007] => -5
                                [1008] => -17
                                [1046] => -14
                                [1050] => -5
                                [1051] => -18
                                [1054] => -19
                                [1062] => -5
                                [1064] => -2
                                [1100] => -21
                                [1136] => -22
                                [1146] => -18
                                [1048] => -3
                            )
                
                        [type] => 
                        [prepared_queries] => 
                        [prepare_maxstmt] => 0
                        [last_query] => select judge_id,lastname, firstname from judges order by lastname limit 5
                        [fetchmode_object_class] => stdClass
                        [options] => Array
                            (
                                [persistent] => 
                                [optimize] => performance
                                [debug] => 0
                                [seqname_format] => %s_seq
                            )
                
                        [dbh] => 
                        [dsn] => Array
                            (
                                [phptype] => mysql
                                [dbsyntax] => mysql
                                [username] => somebody
                                [password] => very_secret
                                [protocol] => tcp
                                [hostspec] => hal
                                [port] => 
                                [socket] => 
                                [database] => interpreters
                            )
                
                    )
                
                [result] => Resource id #9
                [row_counter] => 
                [limit_from] => 
                [limit_count] => 
                )
                

                You see that the PEAR Result is more metadata than data. You call the fetchXXX() and getXXX() methods on the result object to get to the actual data.

                If you look at the data structure that getAssoc() returns, you'll see it's a 2-dimensional array where the first column supplies the keys and the values are an array containing the data from the remaining columns. I bet you could get Smarty to loop through that. Then I'd be saving this extra step and life would be beautiful. So I'm trying to get the hang of Smarty's section looping thing.

                Thank you again.

                  2 months later

                  Smarty I found it hard to understan
                  this is my php file

                  $result=$db->Execute("Select * from  cat");
                   while(!$result->EOF){
                     print($result->Fields['name']);
                  
                    $result1=$db->Execute("Select * from subcat where  cat_id='".$result->Fields['id']."' ");
                       while(!$result1->EOF){
                         print($result1->Fields['name']);
                        $result1->MoveNext();
                        }
                  $result->MoveNext();
                  }
                  

                  how to assign for smarty for this kind of quries please help me

                    Write a Reply...