#PDO Cheatsheets
#Open a connection
try {
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
} catch (PDOException $e) {
echo $e->getMessage();
}
#Close a connection
$dbh = null;
#Insert
try {
$sth = $dbh->prepare('INSERT INTO posts(name) VALUES (:name)');
$sth->bindParam(':name', $name);
$sth->execute($data);
} catch (PDOException $e) {
echo $e->getMessage();
}
#Update
try {
$sth = $dbh->prepare('UPDATE posts SET name = :name WHERE id = :id');
$sth->bindParam(':name', $name,PDO::PARAM_STR);
$sth->bindParam(':id', $id,PDO::PARAM_INT);
$sth->execute($data);
} catch (PDOException $e) {
echo $e->getMessage();
}
#Delete
try {
$sth = $dbh->prepare('DELETE FROM posts WHERE id = :id');
$sth->bindParam(':id', $id,PDO::PARAM_INT);
$sth->execute($data);
} catch (PDOException $e) {
echo $e->getMessage();
}
#Read
#Read a single record
try {
$sth = $dbh->prepare('SELECT * FROM posts WHERE id = :id');
$sth->bindParam(':id', $id,PDO::PARAM_INT);
$sth->execute($data);
$post = $sth->fetch();
} catch (PDOException $e) {
echo $e->getMessage();
}
#Read multiple records
try {
$sth = $dbh->prepare('SELECT * FROM posts');
$sth->execute($data);
$posts = [];
while($row = $stmt->fetch()) {
$posts[] = $row;
}
} catch (PDOException $e) {
echo $e->getMessage();
}