Page 1 of 1

Using databases in a class

Posted: Thu Jan 24, 2008 5:52 am
by Steve Mellor
I'm comparatively new to writing my own classes. I've never come across this problem before and needed some guidance.

I'm writing a class to replace certain keywords on an article page with internal links to the rest of the site. Here's what I have so far which works.

Code: Select all

 
<?php
 
    class replace {
    
        var $text       = "";
        
        function ReplaceString($text) {
 
                $keyword = "Phasellus";
                                $link = "home.php";
                $replace = "<a href=\"$link\">$keyword</a>";
                $text = str_replace($keyword, $replace, $text);
            
            echo $text;
            
        }
    
    }
 
?>
 
Currently I'm using Lorem Ipsum text in place of an actual article hence the keyword 'Phasellus'. What I want to do now is take a database of keywords and links and use that to populate the $keyword and $link variables (throwing the whole thing in to a loop). My question is; what is the best way of connecting to a database from a function within a class?

Re: Using databases in a class

Posted: Thu Jan 24, 2008 9:03 am
by Inkyskin
You can connect to a database from within a class exactly the same way as normal, same goes for functions too

Re: Using databases in a class

Posted: Fri Jan 25, 2008 6:19 am
by Steve Mellor
Thanks. I've finished the class which looks like this:

Code: Select all

 
<?php
 
    class replace {
    
        var $text       = "";
        var $host       = "";
        var $data       = "";
        var $user       = "";
        var $pass       = "";
        
        function ReplaceString($text) {
 
            $connect = mysql_connect($this->host, $this->user, $this->pass) or trigger_error(mysql_error(),E_USER_ERROR);
            mysql_select_db($this->data, $connect);
            
            $query_key = "SELECT * FROM `keylist` ";
            $key = mysql_query($query_key, $connect);
            $row_key = mysql_fetch_assoc($key);
            
            do{
            
                $keyword = $row_key['keyword'];
                $keyword2 = ucwords($keyword);
                $link = $row_key['link'];
                $replace = "<a href=\"$link\" class=\"replace\">$keyword</a>";
                $replace2 = "<a href=\"$link\" class=\"replace\">$keyword2</a>";
                $text = str_replace($keyword, $replace, $text);
                $text = str_replace($keyword2, $replace2, $text);
            
            }while($row_key = mysql_fetch_assoc($key));
            
            echo $text;
            
        }
    
    }
 
?>
 
I'm happy with it, it seams to work the way I want it to.