how to connect to another db with doctrine on zend framework - php

I use Zend Framework 1.10 with integration on Doctrine 1.2.
in the application.ini file, i declare the 'dsn' to connect to database.
in my application i need to connect to another db to run some queries.
how can i do it ?
i only need to run query , i don't want to generate all the Models for this DB.
right now in the bootstrap.php i do the default connection :
protected function _initDoctrine()
{
$this->getApplication()->getAutoloader()
->pushAutoloader(array('Doctrine', 'autoload'));
spl_autoload_register(array('Doctrine', 'modelsAutoload'));
$doctrineConfig = $this->getOption('doctrine');
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_AUTO_ACCESSOR_OVERRIDE, true);
$manager->setAttribute(
Doctrine::ATTR_MODEL_LOADING,
$doctrineConfig['model_autoloading']
);
Doctrine_Core::loadModels($doctrineConfig['models_path']);
$conn = Doctrine_Manager::connection($doctrineConfig['dsn'],'doctrine');
$conn->setAttribute(Doctrine::ATTR_USE_NATIVE_ENUM, true);
Doctrine_Core::generateModelsFromDb('models', array('doctrine'), array('generateTableClasses' => true));
return $conn;
}

You can also store Doctrine instances in Zend_Registry and retrieve the one you are wanting later.
$conn1 = Doctrine_Manager::connection(...);
Zend_Registry::set('conn1',$conn1);
$conn2 = Doctrine_Manager::connection(...);
Zend_Registry::set('conn2',$conn2);
Then later you can retrieve it by doing the following:
$conn1 = Zend_Registry::get('conn1');
$conn2 = Zend_Registry::get('conn2');

This assumes regular Doctrine without the use of Zend or alike!
It is already there in your code, you just need to add another line with your connection. I suggest http://www.doctrine-project.org/projects/orm/1.2/docs/manual/connections/en as a good read since it deals extensively with this problem. To get an better idea what I am talking about:
$conn = Doctrine_Manager::connection($doctrineConfig['dsn'],'doctrine');
This is a connection with the name doctrine, to make a second connection, simply create another connection with another name like
Doctrine_Manager::connection($doctrineConfig['dsn'],'second_connection');
Now you have two connections, your already known doctrine and the newly created second_connection.
Read the link from above to see how to handle the retrieval of differen connections. When querying the models, you can define what connection you want to use as an optional parameter.

Just add another dsn for your other DB, and connect to that one using PDO...
As a matter of fact, we defined our databases in the Zend config as follows (using XML), to cater for multiple DB connections :
<databases>
<db_one>
<adapter>pdo_mysql</adapter>
<params>
<dbname>...</dbname>
<username>...</username>
<password>...</password>
<host>...</host>
<port>...</port>
</params>
</db_one>
<db_two>
<adapter>pdo_mysql</adapter>
<params>
<dbname>...</dbname>
<username>...</username>
<password>...</password>
<host>...</host>
<port>...</port>
</params>
</db_two>
</databases>
(Of course they're not really called db_one and db_two, but have a proper name :p).
edit
You could initialize the DB connections as follows (call this somewhere in your bootstrap) :
private function initDb()
{
foreach ($this->config->databases as $name => $database) {
try {
$db = Zend_Db::factory($database);
// Hack for MySQL utf8 encoding...
if ($database->adapter == 'pdo_mysql') {
$db->getConnection();
$db->query('SET NAMES utf8');
}
Zend_Registry::set($name, $db);
} catch (Zend_Db_Adapter_Exception $e) {
throw new Application_Exception($e->getMessage());
} catch (Zend_Exception $e) {
throw new Application_Exception($e->getMessage());
}
}
}
Then, if you want to perform a query on db_two anywhere in your code, you can use :
$db = Zend_Registry::get('db_two');
$stmt = $db->query('select ... from ...');
And use fetch() or fetchAll() on $stmt as you see fit.
BTW You don't have to use Zend_Registry and open all connections on every request of course, so just consider this as an example implementation, not as a guideline on how to solve your problem.

Related

Pros and cons of connecting more than one database in single script

Let's say user have two databases hosted on single host and I need to connect to both of them so that I can use any table anytime without adding connection code multiple times.
I have implemented this in CodeIgniter with adding authorization details of both databases in database.php file and to load required database with $this->load->database('dbname'); in script.
Now, for core PHP, we can do this like:
mysql_connect ('host','user','password','port','dbname'); // connection with one database.
It was connected with my first database.
Now, I want to connect with second database:
1) I have not closed above connection and connected with second one with
mysql_connect ('host','user','password','port','dbname1');.
2) Would it be bad practice to do so ? Would it consume more objects ? Should we be required to close first one anyhow?
It is not neccessary to open 2 connection just to use tables from 2 databases on the same server. You just need to use the database.table notation. Doing that means that you can even join tables from different databases in the same query
SELECT t1.col1, t1.col2, t2.col2, t2.col2
FROM db1.table1 AS t1 JOIN db2.table1 AS t2 ON t1.col1 = t2.col3
So if you have connected to db1 initially you can use db2 tables and the same if you connected to db2 you can use db1 tables.
Have you tried this?
$mysqli1 = new mysqli("example.com", "user", "password", "database1");
$mysqli2 = new mysqli("example.com", "user", "password", "database2");
Why do you need two connections? The pros/advantages of two databases are actually primarily performance issues. But if you are on the same machine actually the only advantage you have, would be a cleaner separation. So it would be better to use one DB with two different prefixes for the table.
So you seperate the diffent data by prefix and not by DB.
You can do this by following object oriented approach
First of all create connection with two databases:
$Db1 = new mysqli('localhost','root','','database1'); // this is object of database 1
$Db2 = new mysqli('localhost','root','','database2'); // this is object of database 2
$query1 = 'select * from `table_name_of_database1`'; // Query to be run on DB1
$query2 = 'select * from `table_name_of_database2`'; // Query to be run on DB2
$result1 = $Db1->query($query1); // Executing query on database1 by using $Db1
$result2 = $Db2->query($query2); // Executing query on database2 by using $Db2
echo "<pre>";
/* Print result of $query1 */
if ($result1->num_rows > 0) {
while($row = $result1->fetch_assoc()) {
print_r($row);
}
} else {
echo "0 results";
}
/*========================================================*/
/* Print result of $query2 */
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
print_r($row);
}
} else {
echo "0 results";
}
Conclusion: When you want to use database1 use $Db1 object and if you want to use database2 then use $DB2.
I don't think how to connect to 2 DBs simultaneously is the problem, as you have successfully done it ( or know how to do it ). I can gather that from your question. So I won't show how to do this. See other answers if you need to.
But to address your issues directly:
Would it be bad practice to do so ? Generally, you should avoid 2 simultaneous DB connection handles as much as possible. If you only need to get data from one DB and use them to do something on the other, your best bet is to put the data from DB1 into appropriate PHP variables, close the connection; then make the second connection. That would be cheaper than keeping 2 DB connections open at the same time. However, if you are doing something like INSERT INTO db1.table SELECT FROM db2.table AND ALSO NEED TO COMMIT OR ROLLBACK depending on success or failure of some queries, then AFAIK, you need to keep both connections open until your processes are over. You see, there always trade-offs. So you decide based on the need of your application and bear the cost.
As a practical example of this scenario, I once worked on a project where I needed to SELECT a table1, INSERT INTO a table2, if the INSERT succeeds, I delete all the rows from table1, if the DELETE fails, I rollback the INSERT operation because the data cannot live in the two tables at the same time.
Of course, my own case involved only one DB, so no need of a second connection. But assuming the two tables were on different DBs, then that may be similar to your situation.
Would it consume more objects ? No other objects other than the ones pointed out in 1 above, namely the DB connection handles according to your question.
Should we compulsory require to close first one anyhow ? Once again, depending on your application needs.
Instead of mysql_connect use mysqli_connect.
mysqli is provide a functionality for connect multiple database at a time.
Q: What cons are there to connect with other database without closing previous database?
A: When you connect to a database server physically are assigning resources to interact with you, if two databases are on the same server you would unnecessarily using resources that could be used to address other connections or other activities. Therefore you would be right close connections that do not need to continue using.
Q: Is this a appropriate practice to do so ? What is the best way to do so without opening this connection in every script multiple times ? I want this to get done in core php only as I have already know this in codeigniter.
One way SESSIONS, but you can't store database conections in sessions. Read in PHP.net this Warning: "Some types of data can not be serialized thus stored in sessions. It includes resource variables or objects with circular references (i.e. objects which passes a reference to itself to another object)." MySQL connections are one such kind of resource.
You have to reconnect on each page run.
This is not as bad as it sounds if you can rely on connection pooling via mysql_pconnect(). When connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection. The connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).
Reference:
http://php.net/manual/en/function.mysql-pconnect.php
http://www.php.net/manual/en/intro.session.php
Can't pass mysqli connection in session in php
1) Is it possible to connect with more than one database in one script ?
Yes we can create multiple MySQL link identifier in a same script.
2) It should be not like to close one connection with mysql_close and open new one,rather both connection should open at a time and user can use any table from any of the database ?
Use Persistent Database Connections like mysql_pconnect
3) If it is possible,what can be disadvantage of this ? Will there create two object and this will going to create issue ?
I don't think so it create any issue other than increasing some load on server.
You can use like this
$db1 = mysql_connect($hostname, $username, $password);
$db2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('abc', $db1);
mysql_select_db('def', $db2);
For Database 1
mysql_query('select * from table1', $db1);
For Database 2
mysql_query('select * from table2', $db2);
The best way to use multiple databases is to use PDO functions
EXAMPLE
// database cobfigurations
$config= array(
// first database
array(
'type'=>'mysql', // DB type
'host'=>'localhost', // DB host
'dbname'=>'database1', // DB name
'user'=>'root', // DB username
'pass'=>'12345', // DB password
),
// second database
array(
'type'=>'mysql', // DB type
'host'=>'localhost', // DB host
'dbname'=>'database2', // DB name
'user'=>'root', // DB username
'pass'=>'987654', // DB password
),
);
// database connections
$mysql=array();
foreach($config as $con)
{
$con=(object)$con;
$start= new PDO($con->type.':host='.$con->host.';dbname='.$con->dbname.'', $con->user, $con->pass, array(
// pdo setup
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'
));
if ($start && !empty($start) && !is_resource($start))
$mysql[]=$start; // connection is OK prepare objects
else
$mysql[]=false; // connection is NOT OK, return false
}
/**********************
**** HOW TO USE ****
**********************/
// fetch data from database 1
$data1 = $mysql[0]->query("SELECT id, title, text FROM content1")->fetchAll();
if(count($data1)>0)
{
foreach($data1 as $i=>$result)
{
echo $result->id.' '.$result->title.' '.$result->text.'<br>'
}
}
// fetch data from database 2
$data2 = $mysql[1]->query("SELECT id, title, text FROM content2")->fetchAll();
if(count($data2)>0)
{
foreach($data2 as $i=>$result)
{
echo $result->id.' '.$result->title.' '.$result->text.'<br>'
}
}
If you not use PDO before, please read this short tutorial:
http://www.mysqltutorial.org/php-querying-data-from-mysql-table/
Is practicly same like mysql and mysqli connections but is more advanced, fast and secure.
Read this documentations:
http://php.net/manual/en/book.pdo.php
And you can add more then 2 databases
Use PDO supported by php 5 version instead mysql connect
Here is a simple class that selects the required database automatically when needed.
class Database
{
private $host = 'host';
private $user = 'root';
private $pass = 'pass';
private $dbname = '';
private $mysqli = null;
function __construct()
{
// dbname is not defined in constructor
$this->mysqli = new mysqli( $this->host, $this->user, $this->pass );
}
function __get( $dbname )
{
// if dbname is different, and select_db() is succesfull, save current dbname
if ( $this->dbname !== $dbname && $this->mysqli->select_db( $dbname ) ) {
$this->dbname = $dbname;
}
// return connection
return $this->mysqli;
}
}
// examples
$db = new Database();
$result = $db->db1->query( "SELECT DATABASE()" );
print_r( $result->fetch_row() );
$result = $db->db2->query( "SELECT DATABASE()" );
print_r( $result->fetch_row() );
$result = $db->{'dbname with spaces'}->query( "SELECT DATABASE()" );
print_r( $result->fetch_row() );
$con1 = mysql_connect($hostname, $username, $password);
$con2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $con1);
mysql_select_db('database2', $con2);
Then to query database 1 pass the first link identifier:
mysql_query('select * from tablename', $con1);
and for database 2 pass the second:
mysql_query('select * from tablename', $con2);
if mysql's user have permission to two database , you can join two table from two database
etc:
SELECT database1.table.title title1,database2.table.title title2
FROM database1.table
INNER JOIN database2.table
ON (database1.table.id=database2.table.id)

optimize connections to mysql

i have a php site
in index file include connect to db function :
function connect(){
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("database");
}
and i use this function in everywhere i need connection
for example:
<?php
connect();
$lastnews_sql = mysql_query("SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10");
if(mysql_num_rows($lastnews_sql)) {
while($Result123 = mysql_fetch_object($lastnews_sql)) {
?>
and use this selection:
text; ?>
in end of using :
<?php
}
}
mysql_close();
?>
there are more than 10 connect(); and mysql_close(); in index file
so there are too many connection error in index file
how can i optimize this metod ?
A singleton pattern seems to suit this down to the ground.
class Database
{
private static $instance;
public function getInstance()
{
if(self::$instance == null)
{
// Create a connection to the database.
// NOTE: Use PDO or mysqli. mysql is deprecated.
}
return self::$instance;
}
}
Use
In your classes, instead of calling connect, assuming you're using a PDO object, you could do something like:
$db = Database::getInstance();
$statement = $db->prepare("SELECT * FROM tblName WHERE val = :val");
$statement->bindParam(":val", $value);
$statement->execute();
$result = $statement->fetchAll();
Why this pattern ?
A Singleton pattern has the advantage of only having one instance of itself exist at one time. That means that you will only ever create one connection to the database.
Setting this up
Okay, so the first thing you want to do is to make a new file, let's call it Database.php. Inside Database.php, you want to pretty much write the code that I've written, only do NOT use mysql_*. Have a look at the PDO tutorial that I have provided, on how to connect to a database using a PDO object, and then you put that connection code inside the if statement, so it might look something like:
if(self::$instance == null)
{
self::$instance = new PDO('mssql:host=sqlserver;dbname=database', 'username', 'password');
}
Then, to use it in another class, put a require statement at the top. Something like:
require_once('Database.php');
Finally, look at the code I put in the use section, above. That is how you use it in your class.
Useful links
PDO Tutorial : http://php.net/manual/en/book.pdo.php
Singleton Pattern : http://www.oodesign.com/singleton-pattern.html

using PDO with php and mysql in class

i am trying to use PDO in php using classes.
so i have defined one config file like that
<?php
global $configVars;
$configVars['online'] = false;
if(($_SERVER['SERVER_NAME'])!='localhost' and ($_SERVER['SERVER_NAME'])!='abc')
{
$configVars['dbhost'] = "localhost";
$configVars['dbuser'] = "dbuser";
$configVars['dbpassword'] = "dbpass";
$configVars['dbname'] = "dbname";
}
?>
then i have defined class to connect the database
<?php
class dbClass{
var $dbHost,
$dbUser,
$dbName,
$dbPass,
$dbTable,
$dbLink,
$resResult,
$dbh,
$dbPort;
function dbClass(){
global $configVars;
$this->dbHost = $configVars['dbhost'];
$this->dbUser = $configVars['dbuser'];
$this->dbPass = $configVars['dbpassword'];
$this->dbName = $configVars['dbname'];
$this->connect_PDO();
}
function connect_PDO(){
try {
$dbh = new PDO('mysql:host='.$this->dbHost.';dbname='.$this->dbName.'', $this->dbUser, $this->dbPass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected.";
}
catch(PDOException $e) {
echo "I'm sorry Charlie, I'm afraid i cant do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
$dbh = null;
}
}
}
?>
now i have defined another class to select the records from table
<?
class cms extends dbClass
{
function get_rec($id=0)
{
($id==0?$addQuery="":$addQuery=" where id =".$id);
$statement = $dbh->prepare("select * from TABLENAME :name order by id");
$statement->execute(array(':name' => $addQuery));
$row = $statement->fetchAll();
return $row ;
}
}
?>
now when i am using this function in my PHP file like this
<?php
$objCMS=new cms();
$getCMS=$objCMS->get_rec(1);
echo $getCMS[0];
?>
i got following out put
Connected.
Fatal error: Call to a member function prepare() on a non-object in /Applications/XAMPP/xamppfiles/htdocs
i am trying to sort this out from last 2 days but no success.
i am new to PDO and want to use it.
Thanks
You $dbh is declared in the base class but without a specific scope I think it's going to default to 'private'. Hence not visible in the sub class.
Also you aren't calling the constructor. Add a call to 'parent::__construct()' in your sub class. http://php.net/manual/en/language.oop5.decon.php
You are going in wrong direction about solving this one.
If you want to give some object access to database, then that object needs access to database object that provides methods to interact with the database. You got that right.
But, inheritance is "IS A" relationship. And your CMS object is not a database type of object, and doesn't have same function as database object right? CMS object should just use Database and this is called composition. This relationship is also called "HAS A" relationship.
So instead of using Inheritance here, you should use Composition like this:
class CMS
{
protected $db;
// other CMS related stuff
}
$db = new PDO($dsn, $username, $password, $options);
$cms = new User($db);
This way your CMS can use database without using inheritance.
Google about composition vs. inheritance and when to use it.
Also take a look at this answer here:
PHP Mysqli Extension Warning
And read this article and go through examples to understand why
composition is a way to go when providing some class a way to
interact with database.
I know this is not an answer to your question, but you have gone in the wrong direction to solve your problems. I see lots of people use only inheritance so just be aware that there is much more then inheritance to make your objects interact. And in this situation, its just wrong to use Inheritance since your CMS object has nothing to do with Database, they are not the same "type". CMS should only use Database.
Hope this helps!
You need to call dbClass() in your constructor for cms
add this to the cms class
function cms() {
parent::dbClass();
}
and change get_rec to have:
$statement = $this->dbh->prepare("select * from TABLENAME :name order by id");
when using $dbh you need to reference it as $this->dbh
You need to make the $dbh to $this->dbh changes in you need to update connect_PDO() also

How do I select a MySQL database to use with PDO in PHP?

I want to select a MySQL database to use after a PHP PDO object has already been created. How do I do this?
// create PDO object and connect to MySQL
$dbh = new PDO( 'mysql:host=localhost;', 'name', 'pass' );
// create a database named 'database_name'
// select the database we just created ( this does not work )
$dbh->select_db( 'database_name' );
Is there a PDO equivalent to mysqli::select_db?
Perhaps I'm trying to use PDO improperly? Please help or explain.
EDIT
Should I not be using PDO to create new databases? I understand that the majority of benefits from using PDO are lost on a rarely used operation that does not insert data like CREATE DATABASE, but it seems strange to have to use a different connection to create the database, then create a PDO connection to make other calls.
Typically you would specify the database in the DSN when you connect. But if you're creating a new database, obviously you can't specify that database the DSN before you create it.
You can change your default database with the USE statement:
$dbh = new PDO("mysql:host=...;dbname=mysql", ...);
$dbh->query("create database newdatabase");
$dbh->query("use newdatabase");
Subsequent CREATE TABLE statements will be created in your newdatabase.
Re comment from #Mike:
When you switch databases like that it appears to force PDO to emulate prepared statements. Setting PDO::ATTR_EMULATE_PREPARES to false and then trying to use another database will fail.
I just did some tests and I don't see that happening. Changing the database only happens on the server, and it does not change anything about PDO's configuration in the client. Here's an example:
<?php
// connect to database
try {
$pdo = new PDO('mysql:host=huey;dbname=test', 'root', 'root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $err) {
die($err->getMessage());
}
$stmt = $pdo->prepare("select * from foo WHERE i = :i");
$result = $stmt->execute(array("i"=>123));
print_r($stmt->fetchAll(PDO::FETCH_ASSOC));
$pdo->exec("use test2");
$stmt = $pdo->prepare("select * from foo2 WHERE i = :i AND i = :i");
$result = $stmt->execute(array("i"=>456));
print_r($stmt->fetchAll(PDO::FETCH_ASSOC));
If what you're saying is true, then this should work without error. PDO can use a given named parameter more than once only if PDO::ATTR_EMULATE_PREPARES is true. So if you're saying that this attribute is set to true as a side effect of changing databases, then it should work.
But it doesn't work -- it gets an error "Invalid parameter number" which indicates that non-emulated prepared statements remains in effect.
You should be setting the database when you create the PDO object. An example (from here)
<?php
$hostname = "localhost";
$username = "your_username";
$password = "your_password";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
echo "Connected to database"; // check for connection
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Alternatively, you can select a MySQL database to use after a PHP PDO object has already been created as below:
With USE STATEMENT. But remember here USE STATEMENT is mysql command
try
{
$conn = new PDO("mysql:host=$servername;", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("use databasename");
//application logic
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
I hope my code is helpful for requested
As far as I know, you have to create a new object for each connection. You can always extend the PDO class with a method which connects to multiple databases. And then use it as you like:
public function pickDatabase($db) {
if($db == 'main') {
return $this->db['main']; //instance of PDO object
else
return $this->db['secondary']; //another instance of PDO object
}
and use it like $yourclass->pickDatabase('main')->fetchAll('your stuff');

PHP: How Do I Get a MySQL Link Identifier For an Already Open Connection?

When you open a MySQL connection with mysql_connect(), it returns a link identifier. But what if you want to get that link identifier again later in the script? (for example: A plug-in, that needs to open a new database connection, and still access the old one.)
I'm looking for a way to return a link identifier to the last connection opened by mysql_connect(). Is there a function that does this?
Even though the explanation of Anti Veeranna is correct, there is a very straight-forward way to do what you want. The docs for mysql_connect() state that this function has a 4th parameter $new_link , which is false by default. If you call mysql_connect() again with the same parameters, which is probably the case, it would not create a new connection, but instead would return the resource identifier of the old one.
Any time ;)
No, there isn't. You have to record link identifiers yourself. You could define link identifier as a class property, so that you can easily access it from your methods and don't have to worry about passing it as a variable over and over again.
Thanks to everyone for the replies.
I ended up opening my own connection, and when my plug-in was done, the last line reopens the initial connection so the rest of the main script can use the database it expects. It's sloppy, I know, but it doesn't seem like there's a better option in this case. :/
Update:: I've submitted this as a feature request on php.net. The link is: http://bugs.php.net/bug.php?id=49400
You have to store your handle in a var.
$link = mysql_connect($host, $login, $pass);
And you can reuse $link along your script, before a new HTTP request.
You either have to store the link identifier yourself as mentioned in other answers OR you can simply omit it, the mysql_* functions can reuse the existing handle
mysql_query help explains it like this:
resource mysql_query ( string $query [, resource $link_identifier ] )
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed.
I would not use that reuse behaviour myself though, unless you are completely sure that your application (or any plugins, etc) are not opening any new connections to other databases.
Use mysql_pconnect, that will do what you want.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
You could also use a static or singleton class to handle connection pooling for you.
<?php
class dbConnectionPooler
{
static var $connections = array();
private static function createConnection($host, $username, $password, $db) {
$connection = mysql_pconnect($host, $username, $password);
if (FALSE !== $connection) {
$result = mysql_select_db($db, $connection);
if (FALSE !== $result) {
self::$connections[self::getConnectionHash($host, $username, $password, $db)] = $connection;
return $connection;
}
}
}
private static function getConnectionHash($host, $username, $password, $db) {
return md5($host. $username. $password. $db); // use your favourite hashing function here
}
public static function getConnection($host, $username, $password, $db) {
$connectionHash = self::getConnectionHash($host, $username, $password, $db);
if (array_key_exists($connectionHash, self::$connections)) {
return self::$connections[$connectionHash];
} else {
return self::createConnection($host, $username, $password, $db);
}
return false;
}
}
$connection = dbConnectionPooler::getConnection("dbhost", "dbuser", "dbpassword", "mydb");
?>

Categories