What are the best practices for accessing a MySQL database on a different server in PHP?

When accessing a MySQL database on a different server in PHP, it is best practice to use PDO (PHP Data Objects) for database connection as it provides a secure and efficient way to communicate with the database. Additionally, make sure to properly configure the database server to allow remote connections and use secure connection methods such as SSL to protect sensitive data during transmission.

// Database connection settings
$servername = "remote_server_address";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create a PDO connection
try {
    $pdo = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}