learn-pdo-php

Learn PDO In 30 Seconds

phpdelusions is my main go to guide for everything php/pdo. But to just get started with PDO you really only need to know a few commands. PDO is great because it’s more secure, prevents SQL injection attacks if used properly, and it’s super simple to use. The question mark is used as a placeholder for variables to be swapped with the arrays passed into the execute statement.

Create a PDO Instance

$dsn = "mysql:host=127.0.0.1;dbname=test;charset=utf8";
$opt = [
PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
	PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
	PDO::ATTR_EMULATE_PREPARES   => false,
	];
$pdo = new PDO($dsn, 'db_username_here', 'db_password_here', $opt);

 

Insert

$pdo->prepare("insert into users (first_name, last_name, age, time) 
values(?, ?, ?, now());")->execute(array($first_name, $last_name, (int)$age));

 

Update

$pdo->prepare("update users set age = ? where id = ?")->execute(array($age, $id));

 

Delete

$pdo->prepare("delete from users where id = ?")->execute(array($id));

 

Select

Selects are a bit more involved but PDO makes them very simple too.

// run query
$stmt = $pdo->prepare('
SELECT
	first_name,
	last_name
FROM users
WHERE id = ?');
$stmt->execute(array($id));

// grab them all
$rows = $stmt->fetchAll();

// loop over results
foreach($rows as $row){
	echo("{$row['first_name']}\n");
}

Leave a Reply

Your email address will not be published.