Two or more MySQL Connections PHP
April 27th, 2010
No comments
Two or more MySQL Connections on PHP
I made this simple php5 class:
<?php ///////////////////////////////////////////////////// // Script: db.php // Description: php5 class handle MySQL connections // Author: Albertux (Alberto Isaac Ayala Esquvias) // FeedBack: <albertoi7@gmail.com> // Web: http://Albertux.AyalaSoft.com (Blog) // Licence: GPLv3 //////////////////////////////////////////////////// class DB { private $settings = array ( 'user' => 'root', 'pass' => 'qwerty', 'db' => 'phpmyadmin', 'host' => 'localhost' ); private $link; // The f**king connection public function __construct($settings = null) { if (!empty($settings)) foreach ($settings as $key => $value) $this->settings[$key]=$value; } public function connect() { $this->link = mysql_connect( $this->settings['host'], $this->settings['user'], $this->settings['pass'] ) or die('<!-- Could not connect: ' . mysql_error().' -->'); //echo '<!-- Connected successfully -->'; // debug mysql_select_db($this->settings['db']) or die('<!-- Could not select database -->'); } public function query($sql, $type = MYSQL_BOTH) // select { $this->connect(); $query = mysql_query($sql, $this->link); while ($row = @mysql_fetch_array($query,$type)) $return[] = $row; @mysql_close($this->link); return $return; } public function exec($sql) // insert, update, delete { $this->connect(); $query = mysql_query($sql, $this->link); $return = @mysql_insert_id(); @mysql_close($this->link); return $return; } public function __toString() // $obj = new DB(); print $obj; { $r = "Settings: "; foreach($this->settings as $key => $value) $r.="$key => $value; "; return $r."\n"; } } ?>
Howto use:
$dbh = new DB(); print $dbh; $result = $dbh->query("YOUR_SQL_QUERY_HERE"); print_r($result); $dbhr = new DB(array("db"=>"other","host"=>"remotehost")); print $dbhr; $result2 = $dbhr->query("YOUR_SQL_QUERY_HERE");
Using framework ?
CodeIgniter:
http://www.gotphp.com/php/codeigniter-multiple-database-support
CakePHP:
http://bakery.cakephp.org/articles/view/master-slave-support-also-with-multiple-slave-support
