Loading ...

PHP PDO to create connection and prepared statements

PHP PDO (PHP Data Objects) is a database access layer that provides a uniform method of access to multiple databases. It allows developers to use a consistent interface for different database systems (e.g., MySQL, PostgreSQL, SQLite). PDO supports prepared statements, which help prevent SQL injection attacks and enhance the security of database interactions.

Key Features of PDO:

  • Database Agnostic: PDO provides a consistent API for different database systems.
  • Prepared Statements: Secure way to execute SQL queries.
  • Transaction Management: Support for transactions.
  • Error Handling: Flexible error handling with exceptions.

Basic Example of Using PDO

Let’s go through a simple example using PDO to connect to a MySQL database, insert a record, fetch data, and use prepared statements.

1. Connecting to a Database:

<?php
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'root';
$password = '';

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


$dsn: Data Source Name, contains the information required to connect to the database.


$username and $password: The database credentials.


PDO::ATTR_ERRMODE: Sets the error handling mode to exceptions.

2. Inserting Data Using Prepared Statements

<?php
try {
    $sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
    $stmt = $pdo->prepare($sql);

    // Bind parameters
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':email', $email);

    // Insert a row
    $name = "John Doe";
    $email = "john.doe@example.com";
    $stmt->execute();

    echo "Record inserted successfully!";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

prepare(): Prepares the SQL query for execution.bindParam():

Binds a parameter to a specific variable.execute():

Executes the prepared statement.

3. Fetching Data

<?php
try {
    $sql = "SELECT * FROM users WHERE email = :email";
    $stmt = $pdo->prepare($sql);

    // Bind the email parameter
    $stmt->bindParam(':email', $email);

    // Set the email to search for
    $email = "john.doe@example.com";
    $stmt->execute();

    // Fetch the result
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    echo "Name: " . $user['name'] . ", Email: " . $user['email'];
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

fetch(PDO::FETCH_ASSOC): Fetches the result as an associative array.

4. Using Transactions

Transactions are useful when you need to execute a series of queries that should either all succeed or all fail.

<?php
try {
    // Begin a transaction
    $pdo->beginTransaction();

    // First query
    $pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");

    // Second query
    $pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");

    // Commit the transaction
    $pdo->commit();

    echo "Transaction successful!";
} catch (PDOException $e) {
    // Rollback the transaction if something failed
    $pdo->rollBack();
    echo "Transaction failed: " . $e->getMessage();
}
?>
  • beginTransaction(): Starts a transaction.
  • commit(): Commits the transaction.
  • rollBack(): Rolls back the transaction in case of an error.

Summary

PDO is a powerful and flexible way to interact with databases in PHP. It offers a consistent interface for different databases and includes features like prepared statements and transactions, which improve security and reliability. By using PDO, you can write more secure and maintainable code, regardless of the database system you are using.

4o

Related Posts

Python QR code Generator Fixing Error

Fixing the ‘Module Has No Attribute’ Error When Importing qrcode in Python Introduction Encountering the error AttributeError: module ‘qrcode’ has no attribute ‘QRCode’ when working with Python’s qrcode module? This…

Read more

QR Scanner Android Application in java

How to Build a QR Code Scanner in Java for Android QR codes are widely used for storing information that can be quickly accessed using a smartphone. In this tutorial,…

Read more

Learn Java Threads in just 10 min

Threading = Allows a program to run multiple task simultaneously Helps improve performance with time-consuming operations (File I/O network communication , or any background task) How to create a Thread…

Read more

Real-time Chat Application with Bootstrap 5 & PHP Socket Programming Tutorial

Building a Real-time Chat Application with Bootstrap 5 and Socket Programming Creating a chat application involves integrating real-time data transfer between a client and a server. By combining Bootstrap 5…

Read more

PHP Socket Programming Tutorial with Example Code and Explanations

PHP Socket Programming: A Comprehensive Guide with Example Socket programming in PHP is a powerful way to enable real-time communication between a client and a server. Through sockets, you can…

Read more

How to Create an API in PHP: A Step-by-Step Guide

APIs (Application Programming Interfaces) have become a core component of web development, enabling communication between different software applications. While PHP is known for building dynamic websites, it’s also highly effective…

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *