I am using PHP to query the MySQL database on my website. Please answer the following questions:
What will happen if I don't use mysql_close() when I am done with querying the database in the end? The connection will remain open? If yes then upto how much time? If no then why?
If I open and close a connection to MySQL at several places in a
webpage, how is the performance affected? i.e. connection is made again everytime some access to database is required on a single webpage.
How is mysql_close() related to performance? Should I open a new connection everytime some access to database is required OR should I keep only one connection and close it in the end?
If I don't close the connection, then if the user is trying to
access some data again, will the new connection be used or the old
open connection will be used?
It will automatically close when the PHP script is done running during destruct phase.
Performance will negatively be affected. Opening a new socket (especially to an external database server) is more expensive and time consuming than just keeping a pointer to the current connection in memory.
See answer no. 2
The access to the data will be performed by a new PHP request. Hence, you will have a new database connection. No problems there.
I'd advise to open your database connection during construct phase, re-use that connection during the entire execution of your script (if it's OO based, assign a class variable for your database connection and use $this->db during the entire script), and close it during destruction (or don't bother at all closing it, as it will be closed anyway, even when not declared specifically).
From php.net :
Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
for performance it depends on situations, how long it is used, for how long it is idle and so on (e.g. long execution). In most cases, there is singleton pattern by which you have one open connection, and make all queries with that open handle. But it's not true all in all, as mysql_connect itself is kind of supports that:
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters.
So basically, mysql_close is not very needed when it comes to short running scripts.
There is negligible performance loss to close a connection, compared to the resource usage of keeping it open when you don't need it. Better to close a connection as soon as you're done with it, and open it again when you need to.
If you use non-persistent connections all opened MySQL connections will be automatically closed when the PHP script finishes execution.
Related
I am accessing a database in a php script by establishing a connection using mysqli_connect function. I observe it is not mandatory to close the connection at the end of the script.
What are the implications of not using mysqli_close() in a connection script created to access mysql database in php?
If you are using cgi, then it is not necessary to close your mysql connections since they close automatically at the end of script execution.
From the documentation:
Note: The link to the server will be closed as soon as the execution
of the script ends, unless it's closed earlier by explicitly calling
mysql_close().
Although it is considered a good practice to close your connection.
If you close the connection yourself:
You have to check the value of $_connected for every single query. This means PHP has to check that the variable $_connected A) exists
B) is a boolean and C) is true/false.
You have to call your 'disconnect' function, and function calls are one of the more expensive operations in PHP. PHP has to check that
your function A) exists, B) is not private/protected and C) that you
provided enough arguments to your function. It also has to create a
copy of the $connection variable in the new local scope.
Then your 'disconnect' function will call mysql_close() which means PHP A) checks that mysql_close() exists and B) that you have provided
all needed arguments to mysql_close() and C) that they are the correct
type (mysql resource).
So if you are not using persistent connections, your MySQL connection will be closed at the end of the page execution. So you dont have to bother about that. And hence no downsides.
If you're fairly sure you're not going to use the connection again, or don't have a class that manages your open connections, closing is good practice. A couple reasons:
If you're looping or something over something that creates connections without closing prior ones, you could eat up all your available DB connections based on whatever limit is set on the sql servers side. Typically this limit is for everyone not per host, so you could prevent others from connecting as well.
From Zend (maybe dated): 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.
When I was writing PHP code with PDO and MySQL, I would always create connections when I needed them within functions like so:
result pseudo_function() {
create and open connection
do stuff
close connection
return result
}
Now, I started programming in C, I have seen that pointers are an interesting way to pass the entire connection as parameter to the function. I was wondering if it would be better to pass the connections between functions until the entire user request is served.
To clarify: For one user request, there could be 1-5 calls to a function that then opens a database, fetches data, does something, closes and returns.
Also does it make a difference performance wise if you keep a connection opened?
The "standard idiom" for most PHP code I've seen seems to be "open the connection, and leave it open".
php.net seems to be down at the moment, but these two links might be of interest:
http://php.net/manual/en/function.mysql-pconnect.php
http://php.net/manual/en/mysqlnd-ms.pooling.php
If you're running Apache, perhaps mod_dbd might be a good solution:
http://httpd.apache.org/docs/2.2/mod/mod_dbd.html
Here's a good discussion on the implications of not closing your connections:
Is it totally reckless to leave mysql connection open through a page?
It's better to keep a connection open and perform 5 operations on that connection than opening a new connection every time.
You can also lazy-load your database with a singleton repository pattern; the repository only opens a connection once, upon next invocations it will return a cached result.
If you develop web applications with PHP, it's common (and I suppose the most efficient way) to open the database connection once and close it when the script terminates. Keeping a connection open while other stuff is done does not really produce any overhead or require any actions at all, but reconnecting every time does.
I have a php application. There is a lot of database operation and i do mysql_connect() to open connection. Do I have to close the connection manually?
In general, after script execution the connections should close automatically. However in some cases (e.g. like yours) you have no other way but to do it manually (make mysql_close($connection) to be the last line of your script).
Alternatively, consider using mysql_pconnect() to have persistent connection, which doesn't close after script completion, and is (implicitly) reused on the next request.
Yes. But you do mysql_connect() many times. you can keep it in seperate file and include where ever needed.
Increase the number of allowable connection in mysql settings should do the trick i guess. But before that make sure on each page you are only opening the mysql connection once. At the end of the script the connection should automatically be closed, so no you dont really have to close it manually.
Use singleton to keep just one open connection on each page.
I am working on implementing use of the mysql class found here in an existing script. The script almost always needs to interact with the database, even if there are times when it does not. What is the best practice in this case? Should I open a connection and keep that open until the end of the script or should I open a connection when I need one, closing it when I'm done, to avoid opening a connection when the script does not need it?
Because connections are rather expensive, as others have pointed out, I'd recommend using a "lazy connect" technique in your database layer. If you have structured your application effectively, your application logic should not be concerned with when connections are opened and closed as this would be encapsulated in the database layer. The database layer, when asked to perform a query, would first check to see if it has an active connection and if not, create one. This way you'll avoid opening connections that are never used and you'll also have a nice separation of logic between your application and the database code.
Well, if you are using a class, the connection should be opened automatically when you instantiate the class, or when the first query is performed. If you never use the class, the connection wouldn't be opened. While it is good practice to close it when you don't need it, it doesn't hurt to let it be closed when the request thread dies.
This can be bad if you don't have a resource limits set in your php.ini file, the request could possible live forever and never close the connection.
If you have a medium-to-high traffic site, you should be thinking about using mysql_pconnect anyways so there is always a connection open and you don't need the overhead of opening one on every request.
Usually you'd only want to open a connection to your database when you need to use that connection. Keeping connections open can increase the chance that part of your code will accidentally, or maliciously through the actions of others, cause unwanted queries to be performed on the database.
That being the case, you should only open the connection before you want to run your queries. If you have a large number of queries, try to open your connection as late in the process as possible.
It is better to have one connection left open for a longer duration than to open and close multiple connections.
If your code is performance-sensitive, then the preferred technique tends to be to use some form of connection pooling and/or persistent processes so that you can open one database connection and then use that connection to service many page requests rather than opening a new connection for each request that needs one.
If your code is not performance-sensitive, then it doesn't really matter anyhow.
Either way, the exact timing of when the database is accessed in the course of handling a specific request isn't that great of a cause for concern.
My personal practice is to open a database connection immediately when a new handler process is spawned, then verify that it's still alive when I start processing each request. The rest of the code is then free to just assume that the connection is available when needed without incurring the cost of connecting while a user is waiting for a response.
What security issues can arise from not closing the database connection after using it? Doesn't PHP automatically close it once a new page loads?
As the mysql_close() documentation says:
Using mysql_close() isn't usually
necessary, as non-persistent open
links are automatically closed at the
end of the script's execution. See
also freeing resources.
Since the connections are managed by PHP there shouldn't be a security risk.
PHP is supposed to be a "shared nothing" architecture. That is, all resources are allocated for every request, and then cleaned up after the request is finished. So resources like memory, file handles, sockets, database connections, etc. should be deallocated or closed.
However, you can use persistent database connections which are not closed, but are re-used for the next request. If you do this, there is some security implication. Any connection state is inherited by the next PHP request. So if your application uses database user-defined variables, or temporary tables, or even LAST_INSERT_ID(), the next PHP request may be able to see privileged data that it shouldn't see.
If you close the database connection to avoid this, you're basically defeating the value of the persistent connection. So you might as well use plain database connections.
I can't say whether or not the page closes the connection (that would depend on whatever is managing it) but in general, it is a good idea to close it when you are done because leaving it open longer will potentially cause a starvation issue for other pages that are processing at the same time which want to connect to the same data source.
Jeff Atwood wrote an interesting blog post on this very subject that you might find interesting.