Database best practises


before i begin to create the backend of the website i wanted to ask a about best practises with databases in php, as im really a .net programmer php is relatively new to me and im not quite clued up on the best practises with databases, i know that its common to have a dbConnect php file with your connection in there, when i require dbConnect and it opens a connection to the database, do i have to then inside my code of the other pages that i create have to close the connection at the end of the coding or do i leave the connection open?

should i be creating connections to the database as i need them or is it better to have a php script that does it for me and include that in every php page i need the database in?


@ckhawand @sulliops will better help you on this. So please be patient when they come online they will help you out asap.


thanks man :slight_smile: much appreciated :smile:


Hello, I am not full stack dev but I have some usefull tips that you could use

1.- I always script the conection.php as open / close conections
2.- I try to create config_db.php as my database server configuration file
3.- the most reliable way to connect to databases with php afaik is using PDO
4.- to avoid all the includes I use to have just one main include for all the other libraries that I would be using concerning DBs at least.
5.- Always use Prepared statements to avoid Injects, long story short… you have to alter your query, adding placeholders in place of variables.
6.- the first layer of protection to your DB will in any language will always come from a good field validation so have that in mind as a must have practice in php as well.
7.- always use bcrypt if you are working with passwords and create your own salt for it.

there is many other options that you could use… you can get some references here as well

hope it help! :eyeglasses::venezuela:


Thanks that makes a ton of sense, placeholders was something I wanted to use to minimise risk of injections so I’ll look into the php version of that. :smiley:


Hey @studio7webdev

By my experience,

Feel free to ask any other question. :wink: