note 101219 deleted from function.mysql-pconnect by danbrown
| From: | danbrown@php.net | Date: | Fri, 03 Dec 2010 16:03:56 +0000 |
| Subject: | note 101219 deleted from function.mysql-pconnect by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-174585@lists.php.net to get a copy of this message | ||
Note Submitter: php-nospam325123 at brainpower dot no-ip dot org
----
in reply of Ron:
your class opens unused connections and with Presit this is a extra load for your mysql servers(it
still has an open connection, so mysql treads), but if you don't mysql_close
(Read on) the connection will be locked to the current request
mysql_close does not close the mysql connection, but it does relese the connection to the pool and
other requests.
the old sitation opens a connection to both servers so regarding mysql_max_connections this is no
loadbalencing.
the updated funciton
<?php
class MySQLConnectionFactory {
static $SERVERS = array(
array(
'host' => 'myHost1',
'username' => 'myUsername1',
'password' => 'myPassword1',
'database' => 'myDatabase1'),
array(
'host' => 'myHost2',
'username' => 'myUsername1',
'password' => 'myPassword2',
'database' => 'myDatabase2')
);
public static function create() {
// Figure out which connections are open, automatically opening any connections
// which are failed or not yet opened but can be (re)established.
$cons = array();
for ($i = 0, $n = count(MySQLConnectionFactory::$SERVERS); $i < $n; $i++) {
$server = MySQLConnectionFactory::$SERVERS[$i];
$con = mysql_pconnect($server['host'], $server['username'],
$server['password']);
if (!($con === false)) {
if (mysql_select_db($server['database'], $con) === false) {
echo('Could not select database: ' . mysql_error());
continue;
}
if(!mysql_ping($con)){//im paranoid(i beleve when a presist conn has the same db as selected
no check is done on the connection)
echo('Ping faild');
contunue;
}
$cons[] = $con;
}
}
// If no servers are responding, throw an exception.
if (count($cons) == 0) {
throw new Exception
('Unable to connect to any database servers - last error: ' . mysql_error());
}
// Pick a random connection from the list of live connections.
$serverIdx = rand(0, count($cons)-1);
foreach($cons as $cnum => $con){
if($cnum == $serverIdx) continue;
mysql_close($con);
}
// Return the connection.
return $cons[$serverIdx];
}
}
?>
before whining about mysql_close try this proc
<?php
$conn = mysql_pconnect('mysql','user','pass');
mysql_select_db($conn,'db');
var_dump($conn);
mysql_close($conn);
var_dump($conn);
var_dump(mysql_query('SELECT * form mysql.users',$conn));
?>
as you can see there is no connection anymore (so the connection is released to the pool(managed by
php)