Is it a must to close the connection in PHP script?
Depending on the configuration of your DB server, there is a limit on the possible number of connections opened to it at the same time.
So, if your script :
does some queries
and, then, does some long calculations without doing any query anymore
It can be interesting to close the connection after having done all your queries -- and to only open the connection when it's becoming needed.
Still, note that connections are closed when the script ends, anyway ; which means that if you don't have a wya to be sure that you have finished doing queries, you don't need to close the connection : keeping it opened allows you to do some additionnal queries whenever it's necessary.
(This is particularly true is your pages are built using several distinct and independant components, that are all susceptible to do DB queries)
For the applications I write, I generally :
Open the connection on the first query (Which means no connection is opened if no query is sent)
Never close the connection : as my pages asre built using lots of components, I have no way of knowing for sure that the connection won't be needed anymore.
Yes, it is. As a general rule is this: open connections as late as possible, and close them as soon as possible. In most modern systems/environments connections are pooled, so there's no problem (performance hit) in constantly opening and closing them.
When the php scrip finishes running, all objects, variables are lost even the db connection.else with the new db connection object. But as rule of thumb, it is better to open connection and close it when you don't need it.
Related
It's php application using mysqli.
Someone else suggested to have db connection closed right after each query.
Current system have singleton database connection, so over-created new connection is not issue here. Only unused open connections.(Say, the script has not finished execution and the database is not closed by itself.)
So it seemed that there is something to balance - between the cost of waiting for the script to finish and multiple unnecessary closings of the db connection per script. I tend to think that the first is safer. But I am not very sure if it's sufficient. For example if I do:
$userA->sendMessageTo($userB);
And inside this:
$userA->send($userB);
$userA->useSomePoints();
$userA->flushPointsBalance();
....
Imagining each method will have some database operation but this is just one script call/request, if the db open/close happens around each query, this will certainly happen more than once, comparing to not closing it right after each query in method scope.
So which way is better?
generally, having your DB wrapper class (or ORM) create a single connection for the entire request and only close it during clean up (either via destructor, or via PHP's cleanup) is okay. if this is a problem, it probably means that something long is happening between your opening and closing of connections, and this is what you should be addressing instead.
causes could be:
slow queries that don't make use of indices
some other high latency blocking IO (file reading, decoding, etc)
you'll get better gains in terms of effort addressing those issues, rather than looking at how you open and close connections.
Hey there -- this is general to any operation calling an SQL server, or anything requiring an open connection at that.
Say I have anywhere from 20 to 1000 Select calls to make for each item in data being looped. For each step, I'll select from sql, store data locally in a struct, then proceed. This is not a very expensive call, so should I keep the connection open for the entire loop? Or should I open and close every step?
How expensive in run time is opening a connection? I would think it'd be better to keep the connection open, but would like to get the correct response for this.
Thanks.
How expensive in run time is opening a connection
This only considers CPU speed and doesn't consider bandwidth.
Keeping an open connection saves on CPU but it blocks other requests from being able to use that connection. So its a trade off. Its tough to say what the "correct response" is without knowing a lot more, but in either case it seems like one is tinkering with tolerances instead of nailing the nominals
That said I typically start by keeping a connection open for the duration of a unit of SQL work and then close it.
Although one thing that does seem a little sketchy is this line
20 to 1000 Select calls to make for each item in data being looped.
Try and do more set based operations instead.
Not just for this loop you should keep connection open for entire request. It is good practice to open connection only once at the beginning and close once (at the very end)
You should change your queries (probably join in the other tables in this case) to include the other tables. Try and get all of your data in one database call.
It's the 1000s of queries that will take a lot of time.
Connections in MSSQL using ADO.NET are cached so it's not like when you close a connection the actual TCP/IP pipe to the database is actually closed. So closing and opening won't take time. But no matter what it is you're doing, when you do it 1000s of times, it all adds up.
Get all of your data in one database call, close the connection and then do what you need to do on your C# code. What I try and follow is one database call per Request-Response cycle.
You should use PDO. It creates a data object for each DB connection and you can reference multiple databases on one page without opening and closing over and over.
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
I also have some public code on Github to jump start you. Search for Wrenbjor on github and look for the PDO repo. I would link it but I'm still new to SO so I can only have one hyper link in a post.
basically i'd like to know if it's preferable to establish a database connection before each database query, and then use mysqli_close() immediately after the relevant section, for every spot in the layout where database information has to be pulled - or if it's better to just open the database connection at the start of the file, and then use mysqli_close() near the end of the file.
One connection per request is more efficient. Only if you do many concurrent updates on the same rows is important to commit (close connection) as fast as posible.
it's better to just open the database connection at the start of the file, then get all the data, then use mysqli_close(), and then call a template to start displaying a page.
Use the connection pooling, so it really doesn't matter how often you request a connection in the code. Applications wishing to be scalable should avoid rapidly creating new connections, as they potentially could have noticeable overhead for encryption setup or waiting for a authentication server.
Is there any reason why I should close the connection after a query or at the end of the script?
What are the benefits of doing/no doing do?
The connection (if not persistent) is always closed at the end of the script, so, in theory, you don't need to close it yourself.
Still, if your PHP script takes lots of time to execute, it's a good idea to close the connection when you don't have to do any request to the database anymore -- at least, if the long calculations are done after the queries.
This is especially true if your application is deployed on a shared hosting : your user account can generally only have a few connections opened at the same time. (That number of simultaneous opened connections can be pretty small on shared hosting ; it's generally bigger on private servers).
The reason we often don't close connections ourselfves is :
we generally don't really know when we have done all our queries -- this is especially true with pages that are made of lots of small "blocks" ; each one of those is independant from the others, and can do queries on its own ; so, when can we close the connection ?
web pages are generally quite fast to generate, so we don't really bother about closing the connection to DB.
The benefit is if you're going to be doing long-running processing but have finished querying the database then there is no point holding open a connection. The same goes for holding the user session open (which blocks other requests).
An example of this might be creating a large PDF report. This might take you 20-30+ seconds to create and write out the file but you get all the data you need in the first second.
Ordinarily however you may as well do it automatically (assuming the connection isn't persistent).
I use lazy connection to connect to my DB within my DB object. This basically means that it doesn't call mysql_connect() until the first query is handed to it, and it subsequently skips reconnecting from then on after.
Now I have a method in my DB class called disconnectFromDB() which pretty much calls mysql_close() and sets $_connected = FALSE (so the query() method will know to connect to the DB again). Should this be called after every query (as a private function) or externally via the object... because I was thinking something like (code is an example only)
$students = $db->query('SELECT id FROM students');
$teachers = $db->query('SELECT id FROM teachers');
Now if it was closing after every query, would this slow it down a lot as opposed to me just adding this line to the end
$db->disconnectFromDB();
Or should I just include that line above at the very end of the page?
What advantages/disadvantages do either have? What has worked best in your situation? Is there anything really wrong with forgetting to close the mySQL connection, besides a small loss of performance?
Appreciate taking your time to answer.
Thank you!
As far as I know, unless you are using persistent connections, your MySQL connection will be closed at the end of the page execution.
Therefore, you calling disconnect will add nothing and because you do the lazy connection, may cause a second connection to be created if you or another developer makes a mistake and disconnects at the wrong time.
Given that, I would just allow my connection to close automatically for me. Your pages should be executing quickly, therefore holding the connection for that small amount of time shouldn't cause any problems.
I just read this comment on PHP website regarding persistent connection and it might be interesting to know:
Here's a recap of important reasons
NOT to use persistent connections:
When you lock a table, normally it is unlocked when the connection
closes, but since persistent
connections do not close, any tables
you accidentally leave locked will
remain locked, and the only way to
unlock them is to wait for the
connection to timeout or kill the
process. The same locking problem
occurs with transactions. (See
comments below on 23-Apr-2002 &
12-Jul-2003)
Normally temporary tables are dropped when the connection closes,
but since persistent connections do
not close, temporary tables aren't so
temporary. If you do not explicitly
drop temporary tables when you are
done, that table will already exist
for a new client reusing the same
connection. The same problem occurs
with setting session variables. (See
comments below on 19-Nov-2004 &
07-Aug-2006)
If PHP and MySQL are on the same server or local network, the
connection time may be negligible, in
which case there is no advantage to
persistent connections.
Apache does not work well with persistent connections. When it
receives a request from a new client,
instead of using one of the available
children which already has a
persistent connection open, it tends
to spawn a new child, which must then
open a new database connection. This
causes excess processes which are just
sleeping, wasting resources, and
causing errors when you reach your
maximum connections, plus it defeats
any benefit of persistent connections.
(See comments below on 03-Feb-2004,
and the footnote at
http://devzone.zend.com/node/view/id/686#fn1)
(I was not the one that wrote the text above)
Don't bother disconnecting. The cost of checking $_connected before each query combined with the cost of actually calling $db->disconnectFromDB(); to do the closing will end up being more expensive than just letting PHP close the connection when it is finished with each page.
Reasoning:
1: If you leave the connection open till the end of the script:
PHP engine loops through internal array of mysql connections
PHP engine calls mysql_close() internally for each connection
2: 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).
I might not be 100% correct here but I believe the odds are in my favour.
You may want to look at a using persistent connections. Here are two links to help you out
http://us2.php.net/manual/en/features.persistent-connections.php
http://us2.php.net/manual/en/function.mysql-pconnect.php
The basic unit of execution presumably is an entire script. What you first of all are wanting to apply resources (i.e. the database) to, efficiently and effectively, is the entirety of a single script.
However, PHP, Apache/IIS/whatever, have lives of their own; and they are capable of using the connections you open beyond the life of your script. That's the signficance of persistent (or pooled) connections.
Back to your script. It turns out you have a great deal of opportunity to be creative about using that connection during its execution.
The typical naive script will tend to hit the connection again and again, picking up locally appropriate scraps of data associated with given objects/modules/selected options. This is where procedural methodology can inflict a penalty on that connection by opening, requesting, receiving, and closing. (Note that any single query will remain alive until it is explicitly closed, or the script ends. Be careful to note that a connection and a query are not the same thing at all. Queries tie up tables; connections tie up ... connections (in most cases mapped to sockets). So you should be conscious of proper economy in the use of both.
The most economical strategy with regard to queries is to have as few as possible. I'll often try to construct a more or less complex joined query that brings back a full set of data rather than parceling out the requests in small pieces.
Using a lazy connection is probably a good idea, since you may not need the database connection at all for some script executions.
On the other hand, once it's open, leave it open, and either close it explicitly as the script ends, or allow PHP to clean up the connection - having an open connection isn't going to harm anything, and you don't want to incur the unnecessary overhead of checking and re-establishing a connection if you are querying the database a second time.