Im trying to optimize some of my PHP code. I found out that most time of my PHP script is spent during the connection to my mysql database at the beginning of the script.
I only connect to the database once at the beginning and close the database connection at the end of the script.
But for each user requesting this page a new connection has to be established.
Is there a way to hold a reference to the database and share it for all requests?
You can make your connection persistent (for PDO use PDO::ATTR_PERSISTENT => true), but my recomandation is to find out why your script is spending a lot of time connecting to mysql and make some improvments there.
Consider this:
skip-auto-rehash
from my.cnf
)Yes, you can achieve that.
If you're using the MySQLi extension (the old one without the i at the end is outdated!), you can create a persistent connection by passing p:
as a prefix to the hostname when creating the instance:
See mysqli::__construct.
If you're really using the old MySQL extension, there's mysql_pconnect for persistent connections.
Alternatively, if you're using PDO, then you can use setAttribute()
to use PDO::ATTR_PERSISTENT
.
Documentation on using persistent connection in PDO
.