I have website which uses database, I have implemented singleton pattern to connect to the database.
But my website uses lots of Iframe or inner pages which in turn connects to database using a singleton pattern in each page.
I have few questions to be clarified
1)if a user A comes to website, he browses 10 pages, does that for all the pages only one connection is created or for every page one connection is created?
2)For all the DB connections amde in the sub pages will use the same connection or a new one ?
3)When the user exists from the website, how to close the DB Connection?
I am finding tricky to close the DB Connection, Suppose in my index.php, if it has menu.php, stats.php and profile.php, I am not able to make out when to close the connection?
What is the best pratice to close the connection?
Website is build on PHP and MYSQL database.
If you use a singleton, then the connection is established once for every request.
For every of the 10 pages.
If you include your sub pages via iframes, then you're opening a new connection for every sub page.
One option would be to have a single entry point for your webpage (a front controller) and then closing the connection, after the request has been handled. If you include your php pages in your index.php file, then close the connection after the include/require statements.
Some developers believe it is good practice to call for a close of connection at the end of their pages. Some of them also spend time freeing variables and arrays at the end of a script. To me this is a waste of bytes. It's ok to do things just because they are good coding practice but in my opinion, we should be aiming for fast loading web pages and the efficient use of databases in the exchange of data (to and from). The fact is, when you close a php script or navigate to another page, unless both pages are using php sessions then the previous page and all that was on it will die. It no longer exists and php dumps it.
There is no way to retrieve any of that information once this happens as it is truly killed.
As for database connections, they close themselves.
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(). This is stated in the manual under mysql_connect();
Once again, there are those that like to put a line of code at the end of their scripts calling mysql_close($DB) but remember the waste of bytes thing?
If it is already being done, leave it along. Just my 2 cents worth.
Related
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 code a simple php/mysql web page, that there is page1.php, page2.php and so on. Because I make use of the database on every page (or at least the 90% of them) I place on the top of them the standard
mysql_connect("localhost"," "," ");
mysql_select_db(" ");
.
.
mysql_close();
with my queries.
My question is do I really need to connect to the database on each page or is there any way to avoid this and still stay connected? Some of the pages are linked to the others and I can make use of SESSIONS to post some variables, but my question goes to something more globalized.
The web works in a disconnected state by nature. Meaning that you have no idea if the client is going to come back for a second request or not.
Regardless you absolutely want to connect/disconnect from the database on every single page. This is the only way to ensure you aren't leaking connections and the site can stay responsive.
Most systems have built in ways to handle connection pooling which makes the act of requesting a new connection very very fast and therefore something you don't have to worry about.
You can use mysql_pconnect for a persistent connection, although its not going to help you that much and it can be a big pain to do properly. Its almost just better to connect on every page, especially if the database server is running on the same machine as the php server.
Try using
mysql_pconnect()
From PHP.net
"acts very much like mysql_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect())."
If you just want to make it so that you don't have to hard code it into the top of every file write the connection code in a file then use require /path/to/file/name.php and it will establish it everytime Note: it might be include and not require.
I'm a learner. Is there a way to stay connected in to the mysql database as the user is taken to the next page.
For example, the db connection is made, the user is logged in, and then goes to the next page to access a table in the database. Instead of having to make the db connection again, is there a way to keep the previous connection active?
Or does it matter at all in a low-traffic site?
I read a post yesterday about something related to sessions, and the responder talked about sending a "header-type" (?) file.
Thank you.
Yes and no. Once the user goes to the next page, for all intents and purposes they are not connected to the database anymore.
Your script (on the next page) will still need to open the connection for them. mysql_pconnect() will ensure the actual connection they used is still available when they want it next, however, it can also cause excess number of apache/mysql connections to wait around uselessly.
I'd strongly suggest not using it unless your benchmarks show that it provides a significant gain in performance. Typically, for most applications (especially when you're learning), I would not bother with persistent connections. Note the warning in the PHP Manual
it wont matter unless you're getting a ton of requests, but php has a mysql_pconnect (pconnect) for persistent connections to mysql. each instance of apache will keep around an active connection to mysql that can be used without reconnecting.
I believe you're looking for something like mysql_pconnect(), which establishes a persistent connection to the database.
I realy cant understand your question, if you have fetched datas from db you usualy do some stuff with it. And if you want fetch data from db you do usualy this points.
Some Framworks and Library makes this points a bit easiyer.
Here is the usual way of the process.
1. Make connection to the db.
2. Select a db.
3. Send a query to db.
4. Fetch the results.
5. Do some funy stuff with it.
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.
At the beginning of each PHP page I open up the connection to MySQL, use it throughout the page and close it at the end of the page. However, I often redirect in the middle of the page to another page and so in those cases the connection does not be closed. I understand that this is not bad for performance of the web server since PHP automatically closes all MySQL connections at the end of each page anyway. Are there any other issues here to keep in mind, or is it really true that you don't have to worry about closing your database connections in PHP?
$mysqli = new mysqli("localhost", "root", "", "test");
...do stuff, perhaps redirect to another page...
$mysqli->close();
From: http://us3.php.net/manual/en/mysqli.close.php
"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."
Just because you redirect doesn't mean the script stops executing. A redirect is just a header being sent. If you don't exit() right after, the rest of your script will continue running. When the script does finish running, it will close off all open connections (or release them back to the pool if you're using persistent connections). Don't worry about it.
There might be a limit of how many connections can be open at once, so if you have many user you might run out of SQL connections. In effect, users will see SQL errors instead of nice web pages.
It's better to open a connection to read data, then close it, then display data and once the user clicks "submit" you open another connection and then submit all changes.