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

What Is PHP PDO

PDO (PHP Data Objects) is a database access layer providing a uniform method of access to multiple databases. It doesn't rewrite SQL or emulate missing features. It allows developers to write portable code with ease.

Here's a simple tutorial on how to use PDO:

1. Connection to a Database:

To begin, you need to create a new instance of the PDO class. The constructor accepts parameters for specifying the database source (DSN), username, password, and an array of driver options.

$dsn = "mysql:host=localhost;dbname=testdb";
$username = "root";
$password = "";

try {
    $pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
    echo $e->getMessage();
}

In the above code, an attempt is made to connect to a MySQL database testdb on localhost with the username root and a blank password.

2. Preparing and Executing SQL Statements:

One of the key features of PDO is the ability to prepare statements for execution. This helps in preventing SQL injection attacks.

$stmt = $pdo->prepare("INSERT INTO users (firstname, lastname, email) VALUES (?, ?, ?)");

$stmt->execute(['John', 'Doe', 'john@example.com']);

In the above example, a statement that inserts a new row into the users table is prepared and executed. The ? in the SQL statement are placeholders that get replaced by the values in the array passed to the execute method.

3. Fetching Data:

You can use the fetch or fetchAll methods to fetch data.

$stmt = $pdo->query("SELECT * FROM users");
while ($row = $stmt->fetch()) {
    echo $row['firstname']." ".$row['lastname']."<br>";
}

In the above code, the query method is used to prepare and execute an SQL statement in one step. The fetch method is then used to retrieve one row at a time from the result set.

4. Error Handling:

By default, PDO silently ignores all errors. However, you can change the error reporting level using the setAttribute method.

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Now, PDO will throw a PDOException whenever an error occurs.

Remember to always use prepared statements or parameterized queries to protect against SQL injection attacks when using PDO. Also, ensure that you catch any exceptions that may be thrown by PDO methods.

  1. Connecting to databases with PDO in PHP:

    • PDO (PHP Data Objects) is a database access layer providing a uniform method of access to multiple 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. Executing SQL queries using PDO:

    • Use the query() method to execute SQL queries.
    $sql = "SELECT * FROM users";
    $result = $pdo->query($sql);
    
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        echo $row['username'] . "<br>";
    }
    
  3. Prepared statements and parameter binding in PHP PDO:

    • Use prepared statements for improved security and performance.
    $sql = "INSERT INTO users (username, email) VALUES (:username, :email)";
    $stmt = $pdo->prepare($sql);
    
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':email', $email);
    
    $username = "john_doe";
    $email = "john@example.com";
    
    $stmt->execute();
    
  4. Fetching and handling query results with PDO:

    • Use fetch() or fetchAll() to retrieve results.
    $sql = "SELECT * FROM users";
    $stmt = $pdo->query($sql);
    
    // Fetch one row
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Fetch all rows
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
  5. Error handling and exception management in PDO:

    • Utilize try-catch blocks for error handling.
    try {
        // PDO code here
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
    
  6. Transactions and rollbacks with PHP PDO:

    • Use transactions for atomic operations and rollbacks for error handling.
    try {
        $pdo->beginTransaction();
        // SQL queries here
        $pdo->commit();
    } catch (PDOException $e) {
        $pdo->rollBack();
        echo "Transaction failed: " . $e->getMessage();
    }
    
  7. Configuring and using different database drivers with PDO:

    • PDO supports various 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";