Thursday, September 24, 2015

Use MySQL persistent database connection for WordPress on Azure App

1. MySQL persistent database connection is recommended for improving performance, it is preferred when you use a remote database server.

   For more information, https://azure.microsoft.com/en-us/blog/how-to-run-wordpress-site-on-azure-websites/

2. Persistent database connection has "timeout" implemented, when you try to use the existing connection after long idle time, you may get

   PHP warning "MySQL server has gone away" because it timed out. To prevent this error, use mysql_ping (or mysqli_ping).

   "mysql_ping" checks whether or not the connection to MySQL server is active and working, if the connection is down, it attempts to reconnect.

3. By default, WordPress use regular (non-persistent) connection. To use persistent database connection, you can modify the code in wp-includes/wp-db.php.

Find original code:

  if ( WP_DEBUG ) {       $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );   } else {    $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );   }

...

Modify it to:

  if ( WP_DEBUG ) {       if ( !mysql_ping($this->dbh) ) {           $this->dbh = mysql_pconnect( $this->dbhost, $this->dbuser, $this->dbpassword, $client_flags );       }   } else {       if ( !mysql_ping($this->dbh) ) {        $this->dbh = @mysql_pconnect( $this->dbhost, $this->dbuser, $this->dbpassword, $client_flags );       }   }

For mysqli, find original code:

if ( WP_DEBUG ) {    mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );   } else {    @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );   }

...

Modify it to:

if ( WP_DEBUG ) {       if ( !mysqli_ping($this->dbh) ) {        mysqli_real_connect( $this->dbh, "p:".$host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );       }   } else {       if ( !mysqli_ping($this->dbh) ) {        @mysqli_real_connect( $this->dbh, "p:".$host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );       }   }

Note: The code is base on the current version WordPress 4.3.1

{{html Body}}
Source: Use MySQL persistent database connection for WordPress on Azure App

No comments:

Post a Comment