PHPのお勉強!

PHP TOP

mysql_pconnect

(PHP 4, PHP 5)

mysql_pconnectMySQL サーバーへの持続的な接続をオープンする

警告

この拡張モジュールは PHP 5.5.0 で非推奨になり、PHP 7.0.0 で削除されました。 MySQLi あるいは PDO_MySQL を使うべきです。詳細な情報は MySQL: API の選択 を参照ください。 この関数の代替として、これらが使えます。

説明

mysql_pconnect(
    string $server = ini_get("mysql.default_host"),
    string $username = ini_get("mysql.default_user"),
    string $password = ini_get("mysql.default_password"),
    int $client_flags = 0
): resource

MySQL サーバーとの持続的な接続を確立します。

mysql_pconnect()は、 mysql_connect()とよく似た動作をしますが、 2 つの大きな違いがあります。

1 番目の違いとして、この関数は接続時にまず 同じホスト、ユーザー名、パスワードを有する(持続的)リンクが すでにオープンされていないかどうかを調べます。 それがみつかった場合、新規の接続をオープンする代わりに そのリンクの ID が返されます。

2 番目の違いは、スクリプトの実行が終了しても SQL サーバーとの接続が 閉じられないということです。そのかわりに、将来再利用されるために リンクがオープンされたままとなります(mysql_close() は、mysql_pconnect() によって確立されたリンクを 閉じません)。

このため、この型のリンクは、'持続的(persistent)'であると言われます。

パラメータ

server

MySQL サーバー。"hostname:port" のようにポート番号を 指定することが可能で、localhost では ":/path/to/socket" のようにソケットへのパスを指定することも可能です。

PHP ディレクティブ mysql.default_host が指定されない場合(デフォルト)、 'localhost:3306' が使用されます。

username

ユーザー名。デフォルト値はサーバープロセスの所有ユーザー名です。

password

パスワード。デフォルト値は空のパスワードです。

client_flags

パラメータ client_flags は、 以下の定数の組み合わせです: 128 (LOAD DATA LOCAL の処理を有効にする)、 MYSQL_CLIENT_SSLMYSQL_CLIENT_COMPRESSMYSQL_CLIENT_IGNORE_SPACE または MYSQL_CLIENT_INTERACTIVE

戻り値

成功した場合に MySQL 持続的リンク ID を、失敗した場合に false を返します。

注意

注意:

この接続方法は、モジュールバージョンの PHP でのみ使用可能であることに 注意しましょう。詳しい情報は 持続的 データベース接続 を参照ください。

警告

持続的接続を利用する場合、MySQL の同時接続数の制限をこえないように Apache や MySQL の設定を多少変更する必要があるかも知れません。

参考

add a note

User Contributed Notes 28 notes

up
9
seawyvern at gmail dot com
14 years ago
(using PHP v5.3.2)
This might help other people who are running into a similar issue. I would occasionally get this error in my apache error log:

PHP Warning: mysql_pconnect(): MySQL server has gone away

It appears the persistent connection mysql_pconnect() was returning had timed out and mysql_pconnect() didn't detect it. To address this issue I added some code to check for this case using mysql_ping() and request another connection from mysql_pconnect() if this situation occurred. It appears that the combination of the checking for the time out with mysql_ping( ) and re-requesting the connection with mysql_pconnect( ) either caused the original connection to re-connect or forced mysql_pconnect() to recognize that the connection had timed out and request a new one. The documentation for mysql_ping( ) says that it will force a re-connect if it detects a timeout, however comments on the documentation page mention that this feature has been disabled for some time. Anyways here is the code I used, hope it helps:

$dbConnection = mysql_pconnect( $myHostname, $myUsername, $myPassword );

if ( !mysql_ping( $dbConnection ) )
{
$dbConnection = mysql_pconnect( $myHostname, $myUsername, $myPassword );
}
up
9
fate_amendable_to_changeNOSPAM at yahoo dot com
22 years ago
To tell mysql_pconnect to connect to mysql on a port other than the default use a colon - eg

mysql_pconnect("127.0.0.1:4444", "user", "pass")

would connect to localhost on port 4444

(useful for ssh tunneling etc)
up
4
script_this at yahoo dot com
21 years ago
in response to uthayakutty76 at yahoo dot com's
30-Jun-2003 12:31 post:

-----------------------------------------------------------
...The problem is that the connection to the MySQL
servers is interrupted very quickly or there is not
connection at all. We found out that when using the
domain of the server instead of "localhost" problems
occur.....
-----------------------------------------------------------

try setting the wait_timeout variable in my.cnf for
mysql very high so the connections aren't ever idle for
that amount of time. ridiculous really, but it works for
localhost or remote database server where as the
localhost solution only works if the database is local i
think.
up
4
mightye (at) mightye (dot) org
20 years ago
Normally you do NOT want to use mysql_pconnect. This function is designed for environments which have a high overhead to connecting to the database. In a typical MySQL / Apache / PHP environment, Apache will create many child processes which lie in idle waiting for a web request to be assigned to them. Each of these child processes will open and hold its own MySQL connection. So if you have a MySQL server which has a limit of 50 connections, but Apache keeps more than 50 child processes running, each of these child processes can hold a connection to your MySQL server, even while they are idle (idle httpd child processes don't lend their MySQL connection to other httpd children, they hold their own). So even if you only have a few pages which actually connect to MySQL on a busy site, you can run out of connections, with all of them not actually being used.

In general use mysql_connect() for connecting to MySQL unless that connection takes a long time to establish.
up
3
david at hundsness dot com
16 years ago
Here's a recap of important reasons NOT to use persistent connections:

* When you lock a table, normally it is unlocked when the connection closes, but since persistent connections do not close, any tables you accidentally leave locked will remain locked, and the only way to unlock them is to wait for the connection to timeout or kill the process. The same locking problem occurs with transactions. (See comments below on 23-Apr-2002 & 12-Jul-2003)

* Normally temporary tables are dropped when the connection closes, but since persistent connections do not close, temporary tables aren't so temporary. If you do not explicitly drop temporary tables when you are done, that table will already exist for a new client reusing the same connection. The same problem occurs with setting session variables. (See comments below on 19-Nov-2004 & 07-Aug-2006)

* If PHP and MySQL are on the same server or local network, the connection time may be negligible, in which case there is no advantage to persistent connections.

* Apache does not work well with persistent connections. When it receives a request from a new client, instead of using one of the available children which already has a persistent connection open, it tends to spawn a new child, which must then open a new database connection. This causes excess processes which are just sleeping, wasting resources, and causing errors when you reach your maximum connections, plus it defeats any benefit of persistent connections. (See comments below on 03-Feb-2004, and the footnote at http://devzone.zend.com/node/view/id/686#fn1)
up
2
matt *at* roughest *dot* net
20 years ago
Be very careful when using persistent connections on a machine running multiple mysql servers. You must specify the correct socket path, otherwise PHP will reuse connections irregardless of what server they are connected to. That is, it will see an open connection with matching parameters and use it, even if the connection is actually for a different server.
up
2
spam at vrana dot cz
21 years ago
Be warned if you use different parameters for mysql_pconnect() in different scripts on server: PHP can create single persistent connection for every set of parameters in each process up to mysql.max_persistent (PHP directive) per process. So even if you have MaxClients Apache directive set lesser then max_connections MySQL directive, you can easily get Too many connections MySQL error.

If mysql.max_persistent is set to other value than -1 (unlimited, default value), connections over this limit are silently denied, so use it with care.

Solution: For servers with potentially unlimited set of connection parameters, forbid persistent connection with mysql.allow_persistent=Off.
up
1
3ch0
18 years ago
pconnect is preferred when you are using a remote database server on a major web site. mysql in particular stays happier with 1 open connection as opposed to 1000 connections a minute =)
up
1
pulstar at mail dot com
21 years ago
I had some problems when connecting to a remote server with mysql_pconnect and using the flag MYSQL_CLIENT_COMPRESS. Sometimes it connect, but many times it give me the error:
Warning: mysql_pconnect(): Unknown database 'XXXXX'

If you have the same problem, try using mysql_connect instead. It worked fine for me. The script will take a long to reconnect each time the page is reloaded, but it will transfer data with compression. This is a little more secure than to send plain data over the Internet and also more faster when transmiting large amount of data.
up
2
Ron
19 years ago
Here's a nifty little class which will load balance across multiple replicated MySQL server instances, using persistent connections, automatically removing failed MySQL servers from the pool.

You would ONLY use this for queries, never inserts/updates/deletes, UNLESS you had a multi-master situation where updates to any database serverautomatically replicate to the other servers (I don't know whether that's possible with MySQL).

Using this class, you get a connection to a MySQL server like this:
$con = MySQLConnectionFactory::create();

Here is the class (you'll need to customize the $SERVERS array for your configuration -- note that you would probably use the same username, password and database for all of the servers, just changing the host name, but you're not forced to use the same ones):

<?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;
}
$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);
$con = $cons[$serverIdx];
// Return the connection.
return $con;
}
}
?>
up
0
m at louislivi dot com
5 years ago
SMProxy
A MySQL database connection pool based on MySQL protocol and Swoole.
https://github.com/louislivi/SMProxy
up
0
shane
13 years ago
The new mysqlnd library, which replaces the old libmysql, should make disappearing connections a thing of the past. It refreshes the connection (either change_user or ping) before trying to use it. (It also uses less memory, and generally has better performance.) I've only tried it with mysqli, but the native extension also uses it. It's available for PHP >= 5.3, MySQL >= 4.1.
up
0
JM
16 years ago
If you get an error message which refers to a failure regarding /var/mysql/mysql.sock, try changing your php.ini so that mysql.default_socket=/tmp/mysql.sock
up
0
federico dot chiesa at tiscali dot it
20 years ago
Be very careful when using persistent connections and temporary tables on MySQL: in MySQL, temporary tables are visible only to the currenct connection, but if you have a persistent connection the temporary tables will supposedly be visible to everybody sharing the same persistent connection. This can lead to major trouble. I suggest to use totally random temporary table names when using persistent connections to avoid major problems.
up
0
markunderscoreconnollyatacmdotorg
20 years ago
I would like to comment on the post from dfischer at qualcomm dot com that proposes spanning transactions over multiple application invocations, in case someone is bold enough to try it.

I'll assume the table types being used are one of those that support transactions, such as InnoDB or BerkeleyDB.

First, there is a question of whether this would work at all. To work at all, the transaction context would have to be preserved across all the invocations of the php code through the web server. Reading the description of http://www.php.net/manual/en/features.persistent-connections.php maintaining transaction context would be at best a coincidence. It would be interesting to find out that this does work on occasion and to understand the ramifications of such behavior. If I happened to get your connection and my action was a cancel, your updates might be gone.

Second, if such a thing did work (occassionally or always), there would be performance implications as the underlying database managed transactions that were pretty much open-ended. A few long-running transactions would likely eat up many resources in a short time and the likelihood of concurrency conflicts could rise. If the mysql_pconnect behavior is to keep transaction open at the end of php processing, then it would probably be better to not define transactions when using mysql_pconnect. And, transactions that were never closed by code (user went out to lunch and got hit by a bus) could hold resources for quite some time (maybe until after rehab).

So, even if such a scheme COULD work, it is not a good idea. The transaction should be committed or rolled back at the end of the user request processing. This allows the DBMS to properly manage resource ultilization and keeps bad things from happening to good data. If mysql_pconnect does not coordinate well with the transaction component of the database engine to always end a transaction at the end of processing a request, then mysql_pconnect should never be used where begin transaction is used.
up
0
dfischer at qualcomm dot com
20 years ago
You also may consider using pconnect if you have transactions that span multiple pages. For example, in applications that I develop, I start a transaction on the moment I query selecting the data that the user plans on editing. I then commit the transactions after the user hits the submit button and the data is committed.

I cannot simply use mysql_connect as then the connection would be terminated at the end of the page and if I did not commit my transaction, it is automatically rolled back.
up