jluniya — 2011-10-20T03:11:55-04:00 — #1
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?
felgall — 2011-10-20T04:03:13-04:00 — #2
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.
jluniya — 2011-10-20T05:15:13-04:00 — #3
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?
lemon_juice — 2011-10-20T08:34:25-04:00 — #4
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:
jluniya — 2011-10-20T23:18:41-04:00 — #5