PromptHub
Database Intermediate 25 views

PDOException (Database Connection)

PHP failed to connect to or communicate with the database server.

Explanation

PDOException is a PHP exception thrown by the PDO database extension when a database operation fails. This is different from Laravel's QueryException as it represents a lower-level connection or driver issue. Common causes include incorrect database credentials, the database server being down, the PDO extension not being installed, or network connectivity issues. The error message may also indicate SSL/TLS connection problems or timeout issues.

Common Causes

  • Incorrect database credentials
  • Database server is down
  • PDO extension not installed
  • Network connectivity issue
  • SSL configuration error

Solution

Verify database credentials in .env (DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, DB_PASSWORD). Ensure the database server is running and accessible from your application server. Check that the required PDO extension is installed and enabled in php.ini (e.g., pdo_mysql, pdo_pgsql). Test the connection with a simple script outside Laravel. Check firewall rules if connecting to a remote database. For SSL connections, verify the certificate paths in your database configuration.

Code Example

// Test database connection in tinker
DB::connection()->getPdo();

// This will throw PDOException if connection fails
try {
    $pdo = DB::connection()->getPdo();
    echo "Connected: " . $pdo->getAttribute(PDO::ATTR_SERVER_VERSION);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

// .env configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=secret

Error Information

Language

php

Framework

laravel

Difficulty

Intermediate

Views

25

Related Errors