Persistent connection support in MySQLi Extension was introduced in PHP 5.3, Persistent connection means it will reuse the connection already established instead of creating and destroying each time. Which will reduces the overhead of creating fresh connections every time.
Like mysql_pconnect in mysql extension, MySQLi does not provide a separate function for opening persistent connection.
To open a persistent connection you must prepend p: to the hostname when connecting. Below is the example of persistent Connection with MySQLi.
Object oriented Method : MySQLi Persistent Connection
$mysqli = new mysqli("p:SERVERNAME", "USERNAME", "PASSWORD", "DATABASE");
Procedural Method : MySQLi Persistent Connection
$dbCon = mysqli_connect("p:SERVERNAME", "USERNAME", "PASSWORD", "DATABASE");
The major drawback of persistent connections is that they can be left in unpredictable states by clients, However MySQLi extension provides built-in cleanup handling code.
Built-in Cleanup includes:
- Rollback active transactions
- Close and drop temporary tables
- Unlock tables
- Reset session variables
- Close prepared statements (always happens with PHP)
- Close handler
- Release locks acquired with GET_LOCK()
This ensures that persistent connections are in a clean state on return from the connection pool, before the client process uses them.
The disadvantage of this could potentially be a little slower, as the code to perform the cleanup needs to run each time a connection is returned from the connection pool.
By compiling PHP with MYSQLI_NO_CHANGE_USER_ON_PCONNECT we can avoid auto Cleanup.