Connect to MySQL with PHP#

This example connects to MySQL service from PHP, making use of the built-in PDO module.

Variables#

These are the placeholders you will need to replace in the code sample:

Variable

Description

MYSQL_URI

Service URI for MySQL connection, from the service overview page

Pre-requisites#

For this example you will need:

Note

Your PHP installation will need to include the MySQL functions (most installations will have this already).

Code#

Add the following to index.php and replace the placeholder with the MySQL URI:

<?php

$uri = "MYSQL_URI";

$fields = parse_url($uri);

// build the DSN including SSL settings
$conn = "mysql:";
$conn .= "host=" . $fields["host"];
$conn .= ";port=" . $fields["port"];;
$conn .= ";dbname=defaultdb";
$conn .= ";sslmode=verify-ca;sslrootcert=ca.pem";

try {
    $db = new PDO($conn, $fields["user"], $fields["pass"]);

    $stmt = $db->query("SELECT VERSION()");
    print($stmt->fetch()[0]);
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

This code creates a MySQL client and opens a connection to the database. It then runs a query checking the database version and prints the response

Note

This example replaces the query string parameter to specify sslmode=verify-ca to make sure that the SSL certificate is verified, and adds the location of the cert.

To run the code:

php index.php

If the script runs successfully, the output is the MySQL version running in your service like:

8.0.28