Search code examples
phpmysqlstatic-variables

Is it a good idea to make mysql connections static?


I'm working on a medium-sized (probably) PHP system which had MySQL connections being opened everywhere throughout different files and, made into global variables for the later included scripts to have access to. Since I'm creating another module, I'd like to avoid globals and keeping the same mysql connection for each page request. My current solution is this:

Class Db {
        static public $dbConnectionArray = array();
}

For every request, the connections would be saved in the static array and referred back to at a later time. What do you think could go wrong? And why?

Would like to hear some opinions on how to best tackle this as I would love to reduce the number of opened connections per script run (currently, one page request invoked about 6-15 mysql connections to at least 3 different databases).


Solution

  • No need to reinvent the wheel. you can use mysql persistent connections to keep connections alive. (http://php.net/manual/en/function.mysql-pconnect.php)

    By using persistent connections, your PHP scripts will reuse the same database connections (as long as the database name & credentials are the same)

    Also, if your databases are on the same host, you should be able to use the same mysql connection by using mysql_select_db() function.