問題描述
我有一個(gè)舊的 PHP/MySQL 應(yīng)用程序,它調(diào)用 mysql_connect().大量現(xiàn)有的下游代碼使用此連接直接或通過包裝器進(jìn)行 mysql_query()
調(diào)用.
I have a legacy PHP/MySQL app that calls mysql_connect(). Tons of existing downstream code makes mysql_query()
calls, either directly or through wrappers, using this connection.
對(duì)于我在應(yīng)用程序上開發(fā)的新代碼,我想開始使用 PDO.
For new code that I develop on the app, I would like to start using PDO.
如果我使用相同的主機(jī)/用戶/密碼/dbname 憑據(jù)建立 PDO 連接,我是否很幸運(yùn),在幕后,PHP 將重新使用原始連接?或者 PHP 是否會(huì)創(chuàng)建到服務(wù)器的兩個(gè)不同的連接(不合需要,盡管完全可以理解)?
If I make a PDO connection using the same host/user/pass/dbname credentials, might I be so lucky that under the hood, PHP will re-use the original connection? Or will PHP create two distinct connections to the server (undesirable, albeit totally understandable)?
謝謝!
推薦答案
如果您使用兩個(gè)不同的 API(即 mysql_*
和 PDO),PHP 將生成兩個(gè)不同的連接.
If you are using two different APIs (i.e. mysql_*
and PDO), PHP will generate two different connections.
并且,作為證明",請(qǐng)考慮這部分代碼:
And, as a "proof", consider this portion of code :
$db = mysql_connect('localhost', 'USER', 'PASSWORD');
$pdo = new PDO('mysql://@localhost/astralblog', 'USER', 'PASSWORD');
sleep(5);
運(yùn)行這將在 MySQL 服務(wù)器上產(chǎn)生兩個(gè)不同的連接——它將休眠 5 秒:
Running this will cause two distinct connections, on the MySQL server -- which will sleep for 5 seconds :
mysql> show processlist;
+----+------------+-----------------+------------+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------------+-----------------+------------+---------+------+-------+------------------+
| 41 | astralblog | localhost:46551 | astralblog | Sleep | 188 | | NULL |
| 42 | astralblog | localhost:46552 | astralblog | Sleep | 188 | | NULL |
| 43 | astralblog | localhost | astralblog | Query | 0 | NULL | show processlist |
| 64 | astralblog | localhost | NULL | Sleep | 4 | | NULL |
| 65 | astralblog | localhost | NULL | Sleep | 4 | | NULL |
+----+------------+-----------------+------------+---------+------+-------+------------------+
5 rows in set (0,00 sec)
(有問題的連接是最后兩個(gè),在我啟動(dòng)PHP腳本時(shí)出現(xiàn),5秒后消失)
這篇關(guān)于從 mysql_connect() 獲取 PHP PDO 連接?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!