Reusing a PDO connection after execute? - php

I would like to know if it's correct to re-use a PDO db connection multiple times ?
For example, I set it up in my controller then pass it as a parameter in a constructor of a class, is it correct to call the same connection (by using a function like get_Database) thoughout all my functions in the class and even pass it as a parameter in another class construct to continue working with the same connection ?
Or should I reopen a connection at some point ?
I was able to get it working by simply passing it around, however I am not quite sure if this would be performing well when going live.

Yes, you should reuse the connection.
Or should I reopen a connection at some point ?
The only reason to open a new connection is if connecting to another database. Otherwise, throughout a single script only one connection should be used.
To achieve this it is important to try and avoid using a static singleton throughout your application, rather learn about dependency injection to design your code to share the same PDO instance to every function or class that needs it.
however I am not quite sure if this would be performing well when going live.
As commented, if you reopen a connection often, it will be a lot slower.
There are many dependency injector's out there, and it is almost certainly a matter of opinion, but I like Auryn. Learning about it should help you design code where it is easier to share a single PDO instance, amongst others.

Yes, this is OK and it is better than connecting to the database many times.
The documentation even suggests to use the opened connection between calls to your php script / application:
Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

Related

How to organize the handling of database connections within functions?

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.

Best practice for handling mysql connection in a social network system

Currently, I am dealing with a social network startup. We use php & mysql for back-end development. I have a datamanager.php that have functions which handles the sql connections and queries. I have several functions like signup, login, get_profile, etc.
I have 2 choices for handling mysql connection
1) create a globally reachable $connection variable with mysqli_connect(); and don't close the connections until I finish all the database operations.
2) create a function namely db_connect() that returns the connection variable in each database functions. Also, in each database function like login, signup, I close the connection with mysqli_close(); and get another connection variable with db_connect();
So, which choice is better for handling mysql connections and why ?
It's better to keep the MySQL connection open as of performance. Better use a class to handle all mysql connections and somehow pass the instance of the class (i.e. the object itself) to all other functions/classes which need it. Within the class you could establish the connection ONCE and than keep it!
Firstly, on the assumption that you are building something that needs to have a long shelf life, and scale to lots of users, with a roadmap for new features, I'd encourage you to use an off-the-shelf PHP framework; Zend or Symfony seem to be the front runners. These frameworks provide a lot of the plumbing for you, so you won't have to worry about database connections.
However, specifically answering your question, I'd encourage you to use mysql_pconnect - it frees you up from worrying about opening and closing connections. You do need to read the manual, it's not totally straightforward...

Is it a good idea to make mysql connections static?

I'm working on a medium-sized (probably) PHP system which had MySQL connections being opened everywhere throughout different files and, made into global variables for the later included scripts to have access to. Since I'm creating another module, I'd like to avoid globals and keeping the same mysql connection for each page request. My current solution is this:
Class Db {
static public $dbConnectionArray = array();
}
For every request, the connections would be saved in the static array and referred back to at a later time. What do you think could go wrong? And why?
Would like to hear some opinions on how to best tackle this as I would love to reduce the number of opened connections per script run (currently, one page request invoked about 6-15 mysql connections to at least 3 different databases).
No need to reinvent the wheel. you can use mysql persistent connections to keep connections alive. (http://php.net/manual/en/function.mysql-pconnect.php)
By using persistent connections, your PHP scripts will reuse the same database connections (as long as the database name & credentials are the same)
Also, if your databases are on the same host, you should be able to use the same mysql connection by using mysql_select_db() function.

Where and when to open a database connection

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.

In php how to do session instances?

I'm quite new on php and am trying to learn it.
My question is rather simple but I've been a bit lost while googling for it.
I just want to create an object to manage the database connection. I already did the object and now the problem I'm facing is:
How do i keep it instanced to a session? (So that i don't need to open/close the connection to the database on every page load) And how do I call it afterward?
Are there any way to declare a destroyer, so that when the instance is dying, the connection to the database gets closed?
If you define a __destruct() method on your object, it'll get called when the object is about to be destroyed. You can use this to close your database connection.
You can also use __sleep() and __wakeup() for serializing your objects. They'll get called automatically upon serialization and unserialization. You could use these methods to connect and disconnect as required.
I hate to answer by refuting the question but I think you are going about resolving the problem in the wrong way here.
Rather than worrying about the connection being opened/closed I would suggest using caching, indexing, etc. to solve performance problems when they arise rather than being concerned about the resources involved in establishing a connection.
If you are really concerned about performance why not cache the affected pages and avoid using the database connection at all?
I think you could get the desired effect with this function (don't use this myself, assuming mysql) but be sure to read the comments:
http://www.php.net/mysql-pconnect
I don't think you want to start using sleep/wakeup techniques as to get this working as I understand it would involve creating a whole bunch of separate threads each with its own database connection which will just sap your resources and produce the opposite of the intended effect.

Categories