If I use a class to work with the database, I create a new object of this class, from which I call the function to execute the query, I connect to the database, execute the query, close the connection. I process the data, bring it to the page.

In theory, the script worked and disappeared.

When you re-request from the received page - again repeat the same action? Or something can be saved in the session, so as not to recreate the object?

I want to see an example (scheme) of the actions I described in the correct form.

On different sites they write differently, in the comments there are a lot of opinions “for” and “against” and it is not quite clear what is right and wrong from all.

  • Well, you can save to the session, of course, but if necessary. If this is a small array of information that is often used and is not subject to change, whether it is all kinds of IDs, client settings, rights, and so on, then it is possible. Or write to object and serialize / deserialize. In principle, the essence is the same, but as it is, on the side. - SLy_huh

2 answers 2

I connect to the database, execute the query, close the connection.

A little bit wrong. connection happens strictly 1 time, closing is not necessary at all

When you re-request from the received page - again repeat the same action?

Yes.

Or something can be saved in the session, so as not to recreate the object?

Not.

I want to see an example (scheme) of the actions I described in the correct form.

  • you create class object. When this happens, the connection to the database.
  • execute request
  • execute request
  • execute request
  • process data, display on page
  • Well, I mean, close the connection after all the requests. - azhirov1991

Save the connection for the second connection in PHP will not work and it is not necessary. It is more correct to save the received data not in a session, but in a cache. If the data is written to the session, then it will be available only to one user.

After a fulfilled request, it is necessary to write the serialized received data in redis, memcached or to a file with some name and with the second request, first look in the cache, and then climb into the database.

  • Ask the cache, if the data is in it and they are not out of date, then take the data from the cache.
  • If the data does not come from the cache then connect to the database, request.
  • After the request, serialization and write the result to the cache.
  • Close the connection.
  • Here you need to take into account that MySQL has its own cache of recent requests, and use the cache level higher - at your discretion. - Daniel Protopopov