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
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:
$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).$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
).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.
Establishing a database connection with PDO in PHP:
$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(); }
Configuring connection parameters with PDO:
$dsn = "mysql:host=localhost;dbname=mydatabase;charset=utf8"; $username = "root"; $password = "";
Handling different database drivers in PHP PDO:
// 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";
Error handling and exception management in PDO connections:
try { $pdo = new PDO($dsn, $username, $password); echo "Connected to the database"; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
Securing database connections with PDO in PHP:
// 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']);
Persistent vs. non-persistent connections with PDO:
$dsn = "mysql:host=localhost;dbname=mydatabase"; $username = "root"; $password = ""; $options = [PDO::ATTR_PERSISTENT => true]; $pdo = new PDO($dsn, $username, $password, $options);
Closing and releasing resources after PDO connections:
$pdo = new PDO($dsn, $username, $password); // Use PDO // Connection is automatically closed when $pdo goes out of scope
Checking and testing the success of a PDO connection:
getAttribute()
to check the connection status.$pdo = new PDO($dsn, $username, $password); $connected = $pdo->getAttribute(PDO::ATTR_CONNECTION_STATUS); echo "Connection status: $connected";