1

What is best, I always open the connection with the server, execute a command and close the connection or open once and execute all the commands and close after?

like:

$connection = mysql_connect($host, $user, $password);

mysql_select_db($database, $connection);

mysql_query($sql);

mysql_close($connection);

or:

$connection = mysql_connect($host, $user, $password);

mysql_select_db($database, $connection);

mysql_query($sql);

mysql_query($other_sql);

mysql_query($other2_sql);

mysql_close($connection);

Considered this in a page .php that we can have commands query in whole de page. You think that __construct to open de connection and __destruct to close the connection are a good ideas?

4

2 回答 2

3

Generally speaking, with a few very specific exceptions, you connect to the DB ONCE at the start of your script, then reuse that connection throughout the script.

While MySQL's connection protocol is fairly fast, you're still wasting a considerable amount of CPU cycles by setting up and tearing down the DB connections. This will be specially true if you're connecting via TCP sockets, forcing an entire new TCP connection to be built for every request.

于 2013-07-08T15:16:27.327 回答
0
  1. Open a single connection to your database.
  2. Perform any needed queries on said database. i.e. Re-use your link identifier / connection resource.
  3. After you've finished running your queries, close the connection manually or do nothing (you can do nothing because the connection will automatically close when the script finishes executing).
于 2013-07-08T15:17:41.440 回答