Storing a database connection in a session variable

Possible duplicate:
Cannot transfer mysqli connection in session in php

Many of us have written PHP applications that require databases; mostly MySQL, but I often used very small MS Access databases for people who are less technically capable so that they can load them / save backups / etc. (regardless of whether this is correct or not, I have no idea).

What I notice is a lot of time spent connecting and executing some of the same requests. Because of this, I had an interesting thought: saving the connection and the possible result sets, which are mostly static in the $_SESSION variable, to reduce the load as the user moves the site.

Obviously, this requires a lot of attention. Things like closing a connection when a session is destroyed is just the beginning.

My question boils down to: is this really possible? And if so, what should I know (besides fixing the session , since this is his own problem, applicable to all sessions)?

+7
source share
4 answers

Even if you can do it (resource or data), this is a bad idea. You will have many simultaneous open connections that will explode your maximum connections very quickly ... especially if its life cycle extends beyond more than 100 ms (depending on your requests) to 20 minutes or more. With open connections, something like MySQL will also not be able to reset the memory allocation, and the whole system seems to be going to hell. In short, this is not what the database has if there is only one user in your code.

As an alternative, I highly recommend caching technologies that are designed specifically to reduce database load and reduce connection time. Using something like the simplest, memcached will significantly improve performance, and you can specify exactly how many system resources are in the cache, allowing the database to do its job of retrieving data when needed.

+10
source

You cannot store database connections or result sets in a session, as these are resources and:

Some data types cannot be serialized, so they are stored in sessions. It includes resource variables or objects with circular references (that is, objects that pass a reference to themselves to another object).

http://php.net/manual/en/intro.session.php

You can extract the result set into a regular array and save it in the session, like any other variable. In any case, this would be a fairly typical use case for sessions. Just be careful not to store too much data in the session, as this can become more complex than fetching from the database.

+13
source

You can check the permanent connections for the connecting part. http://php.net/manual/en/function.mysql-pconnect.php

+1
source

For best use, you should use some configuration files. Sessions are for specific sessions, not global ones.

+1
source

Source: https://habr.com/ru/post/888681/


All Articles