Gari Jaen
Gari Jaen

Reputation: 33

Why is important to reopen a connection to mysql?

I have seen programmers that to this in the same doc:

$connection = mysql_connect("localhost","user","password");
        $request = "firts request";
        mysql_query( $request , $connection );
        mysql_close( $conexion );
$connection = mysql_connect("localhost","user","password");
        $request = "second request";
        mysql_query( $request , $connection );
        mysql_close( $conexion );

The question is what if I do not close the connection?

Upvotes: 2

Views: 652

Answers (2)

MrSimpleMind
MrSimpleMind

Reputation: 8597

First! It is time to use the mysqli_* functions over mysql_*. Why?

About open connection each time...

Remember that database connections take "time" to create, normally you have the database on different hardware than your web solution. This means each connection will involve network exchange and this is expensive in a solution with high load of users/multiple connections. From my "world" we normally use some connection patterns to reuse the connections created using some connection pool. From a database connection pool we reuse the amount connections the exist, we can increase and tune this depends on the enterprise. Now for php you should check the mysqli and p: to achieve similar functionality, see persistent connections

Prepending host by p: opens a persistent connection. mysqli_change_user() is automatically called on connections opened from the connection pool.

Regarding closing the connection, the spec here

Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster.

And if you work on new php application you might also consider start with PDO, mysql_ is easier to migrate to mysqli_ but if this is totally new you really should check PDO. Which will also give you the persistent connection functionallity. Read more at Api choosing, Library choosing and PDO connections

Upvotes: 1

Lelio Faieta
Lelio Faieta

Reputation: 6679

The idea about closing the connection is to handle resources properly. An open connection is consuming some resources on the server.

Also, it can be a security issue to leave a connection open. Anyway as in any other case you should find a balance between the two positions based on how your specific code is working.

My answer works for any connection library you use but note that mysql_ is deprecated and will be soon removed. Consider using myslqi_ or better start using PDO

Upvotes: 0

Related Questions