PDO
7 methodsRepresents a connection between PHP and a database server, providing prepared statements and transactions.
PDO::__construct(string $dsn, ?string $username = null, ?string $password = null, ?array $options = null)Creates a PDO instance representing a connection to a database via DSN.
Parameters
| Name | Type | Description |
|---|---|---|
| dsn | string | Data Source Name (e.g. 'mysql:host=localhost;dbname=test'). |
| username | ?string | Database username. |
| password | ?string | Database password. |
| options | ?array | Driver-specific options. |
Returns
void
Example
<?php
$pdo = new PDO(
"mysql:host=localhost;dbname=test;charset=utf8mb4",
"root",
"secret",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);PDO::query(string $query, ?int $fetchMode = null): PDOStatement|falseExecutes an SQL statement, returning a result set as a PDOStatement. Use for non-parameterized queries.
Parameters
| Name | Type | Description |
|---|---|---|
| query | string | SQL statement to execute. |
| fetchMode | ?int | Optional fetch mode. |
Returns
PDOStatement|false
Example
<?php
$stmt = $pdo->query("SELECT id, name FROM users");
foreach ($stmt as $row) {
echo $row["name"];
}PDO::prepare(string $query, array $options = []): PDOStatement|falsePrepares a statement for execution and returns a PDOStatement object. Use for parameterized queries.
Parameters
| Name | Type | Description |
|---|---|---|
| query | string | SQL statement with placeholders. |
| options | array | Driver options. |
Returns
PDOStatement|false
Example
<?php
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute([":id" => 42]);
$user = $stmt->fetch();PDO::beginTransaction(): boolTurns off autocommit mode and begins a transaction. Changes are not committed until commit().
Returns
bool
Example
<?php
$pdo->beginTransaction();
try {
$pdo->exec("UPDATE accounts SET bal = bal - 100 WHERE id = 1");
$pdo->exec("UPDATE accounts SET bal = bal + 100 WHERE id = 2");
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
}PDO::commit(): boolCommits a transaction, making all changes since beginTransaction() permanent.
Returns
bool
Example
<?php
$pdo->beginTransaction();
$pdo->exec("INSERT INTO logs (msg) VALUES ('hi')");
$pdo->commit();PDO::rollBack(): boolRolls back the current transaction, undoing all changes made since beginTransaction().
Returns
bool
Example
<?php
$pdo->beginTransaction();
$pdo->exec("DELETE FROM users WHERE id = 1");
$pdo->rollBack(); // DELETE is undonePDO::lastInsertId(?string $name = null): string|falseReturns the ID of the last inserted row, or the last value from a sequence.
Parameters
| Name | Type | Description |
|---|---|---|
| name | ?string | Sequence name (some drivers like PostgreSQL). |
Returns
string|false
Example
<?php
$pdo->exec("INSERT INTO users (name) VALUES ('Ann')");
$id = $pdo->lastInsertId();
echo $id; // e.g. "42"