PHP Tutorial

PHP Flow Control

PHP Functions

PHP String

PHP Array

PHP Date Time

PHP Object Oriented

Regular Expression

PHP Cookie & Session

PHP Error & Exception handling

MySQL in PHP

PHP File Directory

PHP Image Processing

PHP Use PDO To Connect To The Database

PDO (PHP Data Objects) is a database access abstraction library provided by PHP. It provides a unified API for accessing a variety of different databases, allowing you to switch databases with minimal code changes.

Here's a basic example of using PDO to connect to a MySQL database:

<?php
$host = 'localhost';
$db   = 'testdb';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

Here's a breakdown of the code:

  • The $dsn variable contains the data source name, which tells PDO what type of database you're using (mysql), where the database is hosted (localhost), the name of the database (testdb), and the character set to use (utf8mb4).
  • The $options array contains various settings for the PDO object. We're setting it to throw exceptions when errors occur (PDO::ERRMODE_EXCEPTION), return rows as associative arrays (PDO::FETCH_ASSOC), and turn off emulated prepared statements (PDO::ATTR_EMULATE_PREPARES).
  • We then attempt to create a new PDO instance. If an error occurs while trying to connect to the database, it will throw a PDOException and the error message will be printed.

After establishing the connection, you can then use the $pdo object to run SQL queries on your database. For example, to fetch all rows from a table called users, you could do:

$stmt = $pdo->query('SELECT * FROM users');
while ($row = $stmt->fetch()) {
    echo $row['name'] . "\n";
}

Remember, you should always use prepared statements to protect against SQL injection attacks. Here's an example of how to do this with PDO:

$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();

In this example, $email is a variable containing the email address you're looking for. The ? is a placeholder that gets replaced by the value of $email when the statement is executed.

  1. Establishing a database connection with PDO in PHP:

    • PDO provides a uniform way to connect to different databases.
    $dsn = "mysql:host=localhost;dbname=mydatabase";
    $username = "root";
    $password = "";
    
    try {
        $pdo = new PDO($dsn, $username, $password);
        echo "Connected to the database";
    } catch (PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
    
  2. Configuring connection parameters with PDO:

    • Connection parameters are specified in the Data Source Name (DSN).
    $dsn = "mysql:host=localhost;dbname=mydatabase;charset=utf8";
    $username = "root";
    $password = "";
    
  3. Handling different database drivers in PHP PDO:

    • PDO supports different database drivers (MySQL, PostgreSQL, SQLite, etc.).
    // MySQL example
    $dsn = "mysql:host=localhost;dbname=mydatabase";
    $username = "root";
    $password = "";
    
    // PostgreSQL example
    $dsn = "pgsql:host=localhost;dbname=mydatabase";
    $username = "postgres";
    $password = "password";
    
    // SQLite example
    $dsn = "sqlite:/path/to/database.db";
    
  4. Error handling and exception management in PDO connections:

    • Use try-catch blocks for error handling.
    try {
        $pdo = new PDO($dsn, $username, $password);
        echo "Connected to the database";
    } catch (PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
    
  5. Securing database connections with PDO in PHP:

    • Avoid hardcoding sensitive information.
    • Use separate configuration files.
    • Apply proper permissions to database users.
    // Config.php
    return [
        'dsn' => "mysql:host=localhost;dbname=mydatabase;charset=utf8",
        'username' => "root",
        'password' => "securepassword",
    ];
    
    // Usage
    $config = include('Config.php');
    $pdo = new PDO($config['dsn'], $config['username'], $config['password']);
    
  6. Persistent vs. non-persistent connections with PDO:

    • Persistent connections are maintained across multiple requests.
    $dsn = "mysql:host=localhost;dbname=mydatabase";
    $username = "root";
    $password = "";
    $options = [PDO::ATTR_PERSISTENT => true];
    
    $pdo = new PDO($dsn, $username, $password, $options);
    
  7. Closing and releasing resources after PDO connections:

    • PDO connections are automatically closed when the associated object is destroyed.
    $pdo = new PDO($dsn, $username, $password);
    
    // Use PDO
    
    // Connection is automatically closed when $pdo goes out of scope
    
  8. Checking and testing the success of a PDO connection:

    • Use getAttribute() to check the connection status.
    $pdo = new PDO($dsn, $username, $password);
    
    $connected = $pdo->getAttribute(PDO::ATTR_CONNECTION_STATUS);
    echo "Connection status: $connected";