I've often struggled with database calls--not from a coding standpoint, but from the standpoint of how to make them more self-maintaining. My dream would be this:- An include file which contains the database connection code
- A class within this include file that contains a class
- A constructor which connects to the database
- a destructor which closes the connection
This would be perfect if PHP called the destructor once your class object leaves scope. Then all you'd have to do it place the include file at the top of a page, instantiate an instance of the class where needed, and the server would disconnect from the database at the first appropriate moment. This would be beautifully clean since a parameter sent to the constructor could affect the database user one connects with--a great way to control read/write permissions. I haven't updated to PHP 5 yet, but my understanding is that one must still make an explicit call to the destructor. Please correct me if I am wrong!
That said, how do you personally manage database connections (specifically disconnecting)? Do you use classes at all? A particularly annoying problem for me is when I initialize a connection, close it, and then realize a parent block still wanted to use the database. Oops...
Don't know why you see this as a problem. Create the class and with every instantiation, the database connects.
What I do if I want to use the same database link/connection for multiple objects i can just pass the link to the constructor.
If the link is valid, use it for that new instance, if not, create a new one.
The connection will close once PHP is done. You can make multiple connections.
If you make alot of them and want to close each one, just have a method in your class that closes it!
$myDB->close();
You can just call it after you're done using that instance (ie when you want to sign on with a different username)
Why would you want to connect with different usernames in one PHP call? I just don't see a reason for it.
When an admin type user connects you'll use the root login for example and if a regular user connects you can use a less privilaged mysql user then.
MAX 2 users in mysql and you probably don't have to use both of them in one server call.