I’m working with a mysql database, which involves gathering photos and peoples names and displaying them on a page when a dropdown menu item is selected. I am accessing the database with a php script.
I am used to needing to having to re establish a connection every time I access the database (I hacked around and it worked) but I want this code to look a bit more professional. Does anyone know a way to leave a connection to the database open, so that I don’t need to re establish a connection every time I make a request for data?
I assume you mean keeping the connection open across multiple calls to the server. Within the same script, you should only have to open the connection once.
The mysqli documentation shows how to enable persistent connections.
However, you should benchmark your code to ensure that connecting to the database is really a performance-limiting factor. You can probably find bigger returns by examining the interplay between your application, the queries, and the schema.
With the older mysql_pconnect function, you could run in to issues where old users of a connection left things in a non-clean state:
The mysqli logic does a whole bunch of cleanup for you so that this isn’t an issue.
From the documentation, the cleanup includes: