Basic MySQL Connection in PHP (PDO)

By: Paypal August 4, 2025 PHP

Description

Securely connect to a MySQL database using PHP’s PDO extension — with error handling

Code Snippet

try {
    $pdo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully!";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

Discussion (0)