This is a general question.
I have a website with a page showing many elements of my database. And in this page I have a script where I'm loading these elements.
The the thing I want to know is it alright to load the database at the display of the page, knowing that everytime user will click and reload the page, my script will reload everything again from my database?
Is it a proper way to do it? Like creating an init.php at the first loading of the website, and storing my elements into a $_SESSION?
I don't know if I managed to explain my problem, so please ask me more informations if needed.
The concept is pretty simple.
If you are sending a new request, it is wise to always start a new connection when needed and close it when its done.
But do not store the connection or any results in SESSION, as this can cause security issues. Creating a common script to start adn close a connection is the way to go.
Having said that look at persistent connections is it probably the thing you want.
If you mean connection do DB, I usually do some file, like "db_connect.php", where I connect to my DB and does any other stuff.
Then, everywhere I need to something with it, I include it:
include_once "db_connect.php";
It's good to use include_once instead of include, because you can't include it twice accidently.
Don't store it in SESSION! It's better to include a file ;)
I would avoid the session.
include_once is a good option to include the database connection file.
include_once "db_connect.php";
also, at the end of your file you may also want to include another file that does any database disconnect or cleanup.
include_once "db_disconnect.php";
If you know that every php page on your site you could also use the prepend functionalityy of php for your database connection, which would give every PHP page a database connection.
Do not store the results in session.
If you don't want to perform the query every time the page loads, you can use several caching methods ( both client side and server side ) like.
It's not advisable to store database stuff in the session. If however, that data is is no security risk, and you really really want to avoid database calls. You can go ahead and put them in the $_SESSION
array, or even create cookies and store that data in. Just know that data is very insecure.
Also, lots of info stored in the SESSION stuff's your site memory. It's adviseable to clean out your $_SESSION and/or cookies.
Database calls are not a big deal, they take seconds, are safer;
Another way of storing data to avoid database calls is to cache files using output buffering.