Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

mysql - Getting a PHP PDO connection from a mysql_connect()?

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.

For new code that I develop on the app, I would like to start using PDO.

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)?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Both extensions internally use EG(persistent_list) to store the persistent connection handle. But they create different hashes/keys for this list, so they can't find entries of the respective other extension.

The mysql extension creates keys of the form "mysql_<host&port>_<user>..." while pdo builds "PDO:DBH:DSN=<dsn>:<user>:....". The hashes are used almost like array-keys in a php script. (Over-)simplyfied example:

function pconnect($host,$user,$pass) {
  global $persistent_list;
  $hashkey = sprintf("extensionname_%s_%s_%s", $host, $user, $pass);
  if ( isset($persistent_list[$hashkey]) ) {
    // use stored connection
  }
  else {
    // create new connection
  }
}

So the answer is: No, the connections will not be shared between and re-used by the mysql extension and PDO.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...