Jonob Posted November 15, 2009 Share Posted November 15, 2009 Hi all, Just wanted a quick sanity check here, as I am not sure that I have this right. Assume that I have a single class in a single php file, with multiple functions in the class. Lets say that one of these functions get executed, and it in turn calls a few other functions in the same class, and maybe a few functions in some other classes (files) too. Each function runs one or more queries against a mysql database. Am I correct in thinking that I could just create a single database connection in the first class, and this will be used for all queries that get executed in the current scope? i.e. do something like a class constructor: function __construct() { $connection = new db_connection(); $connection->connect(); } OK, so assuming that this is right, and that I have this constructor in all my classes, and I call Class B from Class A, then it will still connects twice, right? Or, is there a way to specify in the mysql connection function, that if the connection is active, then dont open it again. Thanks for any advice you can give. Quote Link to comment Share on other sites More sharing options...
trq Posted November 16, 2009 Share Posted November 16, 2009 Generally you should pass your connection into any object that needs it. The only class that should actually connect to the database is your database abstraction class. Quote Link to comment Share on other sites More sharing options...
Jonob Posted November 16, 2009 Author Share Posted November 16, 2009 Generally you should pass your connection into any object that needs it. Are you saying that I should connect for each query in each function? Sorry, I am not quite sure what you mean by "any" object. Quote Link to comment Share on other sites More sharing options...
Mchl Posted November 16, 2009 Share Posted November 16, 2009 Optimal solution is to create one connection, and then using it for all queries until script ends (assuming most common situation, where your application works with a single database) Quote Link to comment Share on other sites More sharing options...
Jonob Posted November 16, 2009 Author Share Posted November 16, 2009 Optimal solution is to create one connection, and then using it for all queries until script ends (assuming most common situation, where your application works with a single database) Thanks for confirming this. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.