I got stuck for a bit today on how to configure a PHP PDO connection in a Docker based WordPress dev env. Here’s the function…
/**
* Get the database connection
* @return \PDO database connection instance
*/
public function get_connection() {
$dbname = \TMSC\tmsc_sync()::$tms_db_name;
$username = \TMSC\tmsc_sync()::$tms_db_user;
$password = \TMSC\tmsc_sync()::$tms_db_password;
// Build the DSN string
$host = \TMSC\tmsc_sync()::$tms_db_host;
$port = '3306';
if ( strpos( $host, ':' ) ) {
list( $host, $port ) = explode( ':', $host );
}
$dsn = "mysql:host={$host};port={$port};dbname={$dbname}";
$connection = new \PDO( $dsn, $username, $password, array(
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
) );
// Since MySQL supports it, don't automatically quote parameters to allow control over data types.
// This comes in useful for automatically manipulating the LIMIT clause.
$connection->setAttribute( \PDO::ATTR_EMULATE_PREPARES, false );
// Uncomment to enable connection debugging.
$connection->setAttribute( \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION );
$this->set_mysql_global_defaults( $connection );
return $connection;
}
When this function connects to a Remote AWS/RDS database, we configure it with a FQD for the $host variable. But, when running the same function locally, within our Docker setup, we must use the docker container name “jetpack_mysql” (as defined in the docker-compose.yml file) and not “127.0.0.1” or “localhost”.