Database Connection Instance


I want to make one database connection per user and use the same connection object in all other php pages. How can I do this?

I have a class called dbconn with function as connect(), select(), update(), delete(). The way I know to establish a connection from another php file is to include dbconn class, create object and then call function. But the problem is I will have to repeat this in almost every php file located in different folders.

So, isn’t there any way to initiate the object once and then use it accross php pages?


Yes - you put the code in one file and then include that file in all the web pages. Using require_once to do the include is probably best since the page will not work without it and you don’t want it accidentally being included more than once which also will not work.

require_once or include_once will work fine. So you mean in every php page I will have to call this and initiate object. But I was looking for the option where I can initiate DB connection object once and can use it accross the pages untill user’s session is alive. Is there any way to do this?

No, there isn’t. The way PHP works is that all data associated with a running script are discarded when the script has finished executing and any new instance of this script begins with a clean state. You can use sessions to store data across multiple page requests but sessions cannot store objects which are pointers to database connections, you have to initiate the object every time.

You can use persistent connections to reuse the connection across page requests but still you will need to create a new db object on every request. Persistent connections can lead you to unexpected problems if you don’t know what you are doing so it’s safest not to use them:

Thank you! It helps!