TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 04-22-2011, 03:55 PM   #1 (permalink)
The Wanderer
 
Join Date: Apr 2011
Posts: 10
Thanks: 1
Keshav is on a distinguished road
Default Problem with template class

Well i have created a template class and i works fine with normal content but gives a problem with database content.
the code is like this:
PHP Code:
class temp{

function 
get($file){
$this->page get_file_contents($file);
return 
$this->page;
}

function 
vars($temp_vars){
foreach(
$temp_vars as $keys => $values){
$this->page str_replace('{'.$keys.'}'$values$this->page);
}
return 
This->page;
}

function 
show(){
echo 
$this->page;
}

}

$temp = new temp();

$temp->get('file.html');

// mysql database connection 
while($row mysql_get_num($data)){
$temp->vars(array('var',$row));
}
$temp->show(); 
now what this does is gets the file.html converts into a single string and add it to a variable then in the second function it changes the keys from the html file to original values from the database but it loops only only once and if i echo this->page; in the var() function then it shows the same data multiple times. can anyone help??
Keshav is offline  
Reply With Quote
Old 04-22-2011, 09:37 PM   #2 (permalink)
The Addict
 
tony's Avatar
 
Join Date: Aug 2008
Posts: 336
Thanks: 8
tony is on a distinguished road
Default

I am guessing you have a get_file_contents function in your code because php has file_get_contents.

The other thing is that in the var function your last line is return This->page; which should be return $this->page;

Another thing is that you are passing an array of values when you pass $row so in essence this line: $temp->vars(array('var',$row)); is really $temp->vars(array('var',array('field1'=>'value1','field2 '=>'value2', ...)));.

which in itself in the vars function when you call str_replace you are trying to replace a string for an array which is not possible. I don't know why it didn't give you an error.

That is my take without running the code. In a gist, you might want to take a look at the values you pass around.
tony is offline  
Reply With Quote
Old 04-23-2011, 04:09 PM   #3 (permalink)
The Wanderer
 
Join Date: Apr 2011
Posts: 10
Thanks: 1
Keshav is on a distinguished road
Default

Ya sorry actually i didn't copied the codes i just made it so i remember it so i missed a few part you corrected well how do i convert it from
$temp->var(array('var',$row));
to
$temp->vars(array('var',array('field1'=>'value1','fiel d2 '=>'value2', ...)));
i mean i have only this $row should i add it to field or value and if in field then what should be in value and if in value then what should be in fields sorry i am new to php development.
Keshav is offline  
Reply With Quote
Old 04-23-2011, 08:05 PM   #4 (permalink)
The Addict
 
tony's Avatar
 
Join Date: Aug 2008
Posts: 336
Thanks: 8
tony is on a distinguished road
Default

It seems that you want to show a list of rows, but they show the same data all over, because of the 'var' key. You might want to take a look at at using a combination of extract and to the output buffer functions.

Kohana has a simple enough class that you can take a look to learn more about it
tony is offline  
Reply With Quote
Old 05-09-2011, 05:27 AM   #5 (permalink)
The Wanderer
 
Join Date: Apr 2011
Posts: 10
Thanks: 1
Keshav is on a distinguished road
Default

Ok now i have changed a few codes and this is the new script and i learned that its overwriting $this->p so i changed a bit and now its is giving a new problem it only shows the forum descriptions that is DES not the title that is TIT what is going wrong here??

PHP Code:
class temp{
    
    var 
$p = array();
    var 
$built = array();
    
    function 
getdata($file){
        
$this->$file;
        return 
$this->p;
    }
    function 
vars($data){
        foreach(
$data as $k => $v){
            
$this->built str_replace("{".$k."}"$v$this->p);
        }
        echo 
$this->built;
    }
}

$temp = new temp();

$temp->getdata("<h1>{TIT}</h1><BR />{DES}");


mysql_select_db($database_config$config);
$query_bbforum "SELECT * FROM forum";
$bbforum mysql_query($query_bbforum$config) or die(mysql_error());
while(
$row_bbforum mysql_fetch_array($bbforum)){

$temp->vars(array("TIT" => $row_bbforum['title'],
                    
"DES" => $row_bbforum['description']));


Last edited by Keshav : 05-09-2011 at 05:40 PM.
Keshav is offline  
Reply With Quote
Old 05-10-2011, 03:06 PM   #6 (permalink)
The Addict
 
tony's Avatar
 
Join Date: Aug 2008
Posts: 336
Thanks: 8
tony is on a distinguished road
Default

That is because you are always replacing the keys in $this->p which is never changing with the previous replaces, so the only one that you see is the last replace.

You are never appending previous changes. try chaning = to .= in your vars function.

I created this class based on you, using the syntax of PHP5 objects. Maybe you are using PHP4 and that is why you are using that syntax. But I will advice if you can to at least upgrade to PHP5, there are a lot of improvements to objects in that version. Here is my take on the class:

php Code:
<?php
class temp{
    private $p;
    private $built;
                
    public function __construct($file = null) {
        $this->p = is_null($file) ? '' : $file;
        $this->built = '';
    }

    public function getdata($file){
        $this->p = $file;
        return $this->p;
    }

    public function vars($data){
        foreach($data as $k => $v){
            $this->built .= str_replace('{'.$k.'}', $v, $this->p);
        }

        return $this;
    }

    public function output() {
        echo $this->built;
    }
}

$temp = new temp();
$temp->getdata("<h1>{TIT}</h1><br />{DES}\n");
// or $temp = new temp('<h1>{TIT}</h1> <p>{DES}</p>'.PHP_EOL);

$input = array();
foreach(range(1,20) as $n) {
    $input[] = array('title' => 'TITLE '.$n, 'description' => 'desc'.$n);
}

//usign input as dummy text
foreach($input as $vars) {
    $temp->vars(array('TIT' => $vars['title'],
                                        'DES' => $vars['description']));
}

echo $temp->output();
tony is offline  
Reply With Quote
Old 05-11-2011, 07:14 AM   #7 (permalink)
The Wanderer
 
Join Date: Apr 2011
Posts: 10
Thanks: 1
Keshav is on a distinguished road
Default

But why is it still showing like

TITLE 1


{DES}
{TIT}


desc1

i mean the

{DES}
{TIT}

did you got what i mean sorry for my bad english..
Keshav is offline  
Reply With Quote
Old 05-11-2011, 09:29 PM   #8 (permalink)
The Addict
 
tony's Avatar
 
Join Date: Aug 2008
Posts: 336
Thanks: 8
tony is on a distinguished road
Default

I see what you mean.
There is a problem in the vars function you where right with the = instead of concatenating it with .=

But there was another problem in the logic of multiples in a template.
The template class can only handle 1 template and can only replace 1 instance, but you want multiple copies of that template with different values. So I made some changes.
php Code:
class temp{
    private $p;
    private $built;
                
    public function __construct($file = null) {
        $this->getdata(is_null($file)?'':$file);
    }

    public function getdata($file){
        $this->built = $this->p = $file;
        return $this;
    }

    public function reset() {
        $this->built = $this->p;

        return $this;
    }

    public function vars($data){
        foreach($data as $k => $v){
            $this->built = str_replace('{'.$k.'}', $v, $this->built);
        }

        return $this;
    }

    public function output() {
        return $this->built;
    }
}

$temp = new temp("<h1>{TIT}</h1><br />{DES}\n");

$input = array();
foreach(range(1,20) as $n) {
    $input[] = array('title' => 'TITLE '.$n, 'description' => 'desc'.$n);
}

//usign input as dummy text
foreach($input as $vars) {
    echo $temp->reset()
        ->vars(array('TIT' => $vars['title'],'DES' => $vars['description']))
        ->output();
}
You can see that in the loop that we feed the data to the template, it is just reseting the template, to start with the vars. And also that it is echoing because the temp class can't accumulate multiple copies.
tony is offline  
Reply With Quote
The Following User Says Thank You to tony For This Useful Post:
Keshav (05-12-2011)
Old 05-12-2011, 06:17 AM   #9 (permalink)
The Wanderer
 
Join Date: Apr 2011
Posts: 10
Thanks: 1
Keshav is on a distinguished road
Default

Wohh really thanks a million really i don't know how can i replay you back with this... and if you ever thought of creating a forums script them please do let me know..
Keshav is offline  
Reply With Quote
Old 05-24-2011, 11:34 AM   #10 (permalink)
The Wanderer
 
Join Date: Apr 2011
Posts: 10
Thanks: 1
Keshav is on a distinguished road
Default

Ok i did my homework and worked hard on finding out this problem now i have two tables category and sub category and i want to loop is and display all the rows like:
CATEGORY
- SUBCATEGORY
- SUBCATEGORY
- SUBCATEGORY

hope you understood now there are many categories and there subcategories how do i loop it like that?? i use while loop but still no good...

EDIT: It is working good with the same key names but not with different ones...

Last edited by Keshav : 05-24-2011 at 12:03 PM.
Keshav is offline  
Reply With Quote
Old 05-24-2011, 01:21 PM   #11 (permalink)
The Addict
 
tony's Avatar
 
Join Date: Aug 2008
Posts: 336
Thanks: 8
tony is on a distinguished road
Default

My guess is that subcategory has a Foreing Key linking to category making it a 1 to many relationship. The simple solution would be a loop within a loop.
something like
PHP Code:
<?php
$cats = mysql_query('SELECT * FROM `categories`');

while ($cat = mysql_fetch_assoc($cats)) {
  echo $cat['name'].'<br />';
  $subcats = mysql_query('SELECT * FROM `subcategories` WHERE `category_idfk` = '.$cat['id']);
  while ($subcat = mysql_fetch_assoc($subcats)) {
    echo '- '.$subcat['name'].'<br />';
  }
  mysql_free_results($subcats);
}
mysql_free_results($cats);
?>

This is a very simple rudimentary example. But it gives you the idea of how you might go with it.
tony is offline  
Reply With Quote
Old 05-25-2011, 05:54 AM   #12 (permalink)
The Wanderer
 
Join Date: Apr 2011
Posts: 10
Thanks: 1
Keshav is on a distinguished road
Default

No i know that but i want it work with the template class like:

CAT
-SUBCAT

and the CAT will replace and display the category data from the database and SUBCAT will display the subcategory data from the database. i want to make it database driven template class how do i do that? with the same template class only because it doesn't work properly if i call it in different arrays and if i call it from the same array then it won't loop.
Keshav is offline  
Reply With Quote
Old 05-25-2011, 01:47 PM   #13 (permalink)
The Addict
 
tony's Avatar
 
Join Date: Aug 2008
Posts: 336
Thanks: 8
tony is on a distinguished road
Default

Then, you would need to collect the data and then make the loops again. It depends also of how your template file is marked-up.

The template system that you have now, can't handle loops that replaces variables values (for example kohana's views or smarty) instead of replacing plain text. So you would have to make the loops yourself. something probably like this:

PHP Code:
<?php
$cats_res = mysql_query('SELECT * FROM `categories`');
$items = '';
$subitems = ''
$list = new temp('<ul>{ITEMS}</ul>');

while ($cat = mysql_fetch_assoc($cats_res)) {
  $items .= '<li>'.$cat['name']
  $subcats_res = mysql_query('SELECT * FROM `subcategories` WHERE `category_idfk` = '.$cat['id']);

  if(mysql_num_rows($subcats_res) > 0) {
    while ($subcat = mysql_fetch_assoc($subcats_res)) {
      $tmp .= '<li>'.$subcat['name'].'</li>'.PHP_EOL;
    }
    $subitems = $list->reset()
        ->vars(array('ITEMS' => $tmp))->output();
    $items .= PHP_EOL.$subitems;
  }

  $items .= '</li>';
  mysql_free_results($subcats);
}
mysql_free_results($cats);
?>

echo $list->reset()->vars(array('ITEMS'=>$items))->output();

I haven't tested this code, but it is something like this. As you can see it doesn't help to separate the concerns of html and processing code.
tony is offline  
Reply With Quote
Old 05-26-2011, 01:10 PM   #14 (permalink)
The Addict
 
tony's Avatar
 
Join Date: Aug 2008
Posts: 336
Thanks: 8
tony is on a distinguished road
Default

Yeah, free scripts would help you. and even if you are not allowed to use them and tweak them (for whatever reason) you can learn from them too.
tony is offline  
Reply With Quote
Old 05-26-2011, 05:24 PM   #15 (permalink)
The Wanderer
 
Join Date: Apr 2011
Posts: 10
Thanks: 1
Keshav is on a distinguished road
Default

Ya i will try but is there a way to make a template engine that works with str_replace?
Keshav is offline  
Reply With Quote
Old 05-26-2011, 06:09 PM   #16 (permalink)
The Addict
 
tony's Avatar
 
Join Date: Aug 2008
Posts: 336
Thanks: 8
tony is on a distinguished road
Default

There is like the one that we kind of come up in here. but it will be of limited functionality when it comes to looping content.
tony is offline  
Reply With Quote
Old 05-27-2011, 06:06 AM   #17 (permalink)
The Wanderer
 
Join Date: Apr 2011
Posts: 10
Thanks: 1
Keshav is on a distinguished road
Default

Still could you please tell me
EDIT:
Ok i made this but its displaying the main category every time before the subcategory like this:
CATEGORY:
-SUBCATEGORY1
CATEGORY:
-SUBCATEGORY2
CATEGORY:
-SUBCATEGORY3

But i want it like:
CATEGORY:
-SUBCATEGORY1
-SUBCATEGORY2
-SUBCATEGORY3

and its also looping the whole template data every time a new variable is added this is the code:
PHP Code:
class temp{
    var 
$p;
    var 
$b;
    var 
$val = array();
    
    function 
get_temp($file){
        
$this->file_get_contents($file);
        return 
$this->b;
    }
    function 
reset(){
        
$this->$this->b;
        return 
$this->p;
    }
    function 
vars($key$value){
        
$this->reset();
        
$this->val[$key] = $value;
        foreach(
$this->val as $key => $value){
            
$this->str_replace("{".$key."}"$value$this->p);
        }
        return 
$this->p;
    }
    function 
show(){
        echo 
$this->p;
    }
}
$temp = new temp();

$temp->get_temp("temp.html");

mysql_select_db($database_config$config);
$query_bbcat "SELECT * FROM category";
$bbcat mysql_query($query_bbcat$config) or die(mysql_error());
while(
$row_bbcat mysql_fetch_assoc($bbcat)){
$temp->vars("TIT"$row_bbcat['title']);
$temp->vars("DSC"$row_bbcat['description']);

mysql_select_db($database_config$config);
$query_bbsubcat "SELECT * FROM fsubcategory WHERE cid={$row_bbcat['id']}";
$bbsubcat mysql_query($query_bbsubcat$config) or die(mysql_error());
while(
$row_bbsubcat mysql_fetch_assoc($bbsubcat)){
    
$temp->vars("FTIT"$row_bbsubcat['title']);
$temp->vars("FDSC"$row_bbsubcat['description']);
$temp->show();
}


Last edited by Keshav : 05-27-2011 at 06:47 PM.
Keshav is offline  
Reply With Quote
Old 08-11-2011, 06:52 AM   #18 (permalink)
The Visitor
 
Join Date: Aug 2011
Posts: 2
Thanks: 0
benjamin444 is on a distinguished road
Default

It seems that you want to show a list of rows, but they show the same data all over, because of the 'var' key. You might want to take a look at at using a combination of extract and to the output buffer functions.

_________________
MBA consultants in India
benjamin444 is offline  
Reply With Quote
Old 10-18-2012, 12:46 PM   #19 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default

Some conservatives have Coach Factory Outlet pushed that critique further, saying that Mr. Obama’s policies are too costly, often assist the wrong people Louis Vuitton Belts and could have the paradoxical effect of driving up college costs. The dispute turns not just on different Coach Factory Outlet assessments of how policies play out, but on differing philosophical views about the role of government. During Gucci Belts his time in office, Mr. Obama has sharply increased aid to low- and middle-income students, notably through the Pell Grant Coach Factory Outlet program, which grew from $14.6 billion given to 6 million students in 2008, to nearly $40 billion for Coach Factory Outlet almost 10 million students this year. His administration also made it easier to request aid, shortening the Coach Factory Online complex federal application and allowing people to transfer their financial information electronically from the Internal Coach Outlet Online Revenue Service database. But while many education experts laud his efforts, analysts of varying political Coach Outlet Online stripes have also questioned how much impact some of the president’s policies will have, noting that the prices Coach Online Outlet charged by colleges, and student borrowing, continue to climb.But behind the headlines about soaring costs, the Coach Factory Outlet Online reality is more complex and wildly uneven, because a growing number of students receive Coach Outlet Online financial aid, and only relatively high-income families pay those fast-rising sticker prices. Adjusted for Coach Factory Online inflation, the College Board calculates, the average net price changed little over the last decade at private Coach Factory Outlet schools, and rose only modestly at public ones.Defending federal spending, Arne Duncan, the secretary of Hermes Belts education, said that for more than 30 years, college prices had risen even when federal aid had not, leading him to believe Coach Factory Online there was zero correlation.
dashixiong is offline  
Reply With Quote
Old 10-22-2012, 08:43 AM   #20 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default Coach Outlet

You’ve relativelyCoach Outlet recently arrived in New Delhi after living in two of Asia’s other great cities,Coach Outlet Store Online Tokyo and Hong Kong, for several years. Do these cities feel like they’re part of the same continent? Yes, and no. In terms Coach Factory Onlineof infrastructure, they couldn’t be more different. Getting regularCoach Outlet power and water at my house in New Delhi is never a sure thing, even though Coach Purse Outlet OnlineI’m paying the same rent that I paid in Tokyo and almost the same electricity prices. Both Hong Kong and Tokyo are also crowded places,Coach Factory Outlet Online but both cities are incredibly well planned and efficiently run. Efficient is not a word I would use to describe my Coach Bags Outlet Onlineday-to-day life in New Delhi. On the other hand, one thing that I think Hong Kong and New Delhi have in common isCoach Handbags Outlet a shared sense of optimism — a feeling that the best is yet to come. That’s definitely not the feeling you get in Tokyo,Coach Outlet Online or in the U.S. when I go home. It’s a big part of what I find addictive about living and working in this part of the world. You feel like you’re watching the future unfold.
dashixiong is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
Problem using one class within another - class v instance JohnAtYM Advanced PHP Programming 1 05-18-2010 11:05 AM
base classes..... allworknoplay Absolute Beginners 16 05-10-2009 08:09 PM
[Tutorial] Basic tutorial about class basics Tanax Absolute Beginners 14 07-24-2008 01:37 PM
Pure PHP template class. abiko Advanced PHP Programming 1 04-02-2008 05:45 PM
PHP5 Classes A to Z Part 1 quantumkangaroo Advanced PHP Programming 11 04-01-2008 04:21 AM


All times are GMT. The time now is 02:45 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design