2012-01-31

Multiple databases

1/31/2012 08:56:00 AM Posted by Hoàng Dũng No comments
Class Mysql
{

    var $link_resource = NULL;
    var $db_resource = NULL;
    var $info = array();
   
    function __construct($servername,$user,$pass,$data)
    {
        $this->connect($servername,$user,$pass);
        $this->dbselect($data);
    }

    public function connect($servername,$user,$pass)
    {
        $this->link_resource = mysql_pconnect($servername, $user, $pass);
        if ($this->link_resource)
        {
            $this->info['server'] = $servername;
            $this->info['user'] = $user;
            $this->info['pass'] = $pass;
        } else
            $this->show_error('connect failed');
    }
   
    public function dbselect($name)
    {
        $this->db_resource = mysql_select_db($name, $this->link_resource);
        if (!$this->db_resource) {
            $this->show_error('Can\'t use '.$name);
        }
        $this->info['database'] = $name;
    }
   
    public function query($sql)
    {
                $this->dbselect($this->info['database']);
            $query=mysql_query($sql, $this->link_resource) or $this->show_error("Query Error : ".mysql_error());
        return $query;
    }
   
    public function fetch_assoc($resource)
    {
        return mysql_fetch_assoc($resource);
    }
   
    private function show_error($string)
    {
        echo $string;
        exit();
    }

}

$mysql1 = new Mysql('localhost','root','vertrigo','vb4');
$mysql2 = new Mysql('localhost','root','vertrigo','test');

//cac query
$query1 = $mysql1->query("SHOW TABLES");
while ($row = $mysql1->fetch_assoc($query1))
{
    echo $row['Tables_in_vb4'].'
';
}

echo '

';

$query2 = $mysql2->query("SHOW TABLES");
while ($row = $mysql2->fetch_assoc($query2))
{
    echo $row['Tables_in_test'].'
';




0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.