Last active
December 27, 2015 08:39
-
-
Save nqthqn/7297698 to your computer and use it in GitHub Desktop.
PHP: PDO Database CRUD
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// CREATE | |
try { | |
$pdo = new PDO('mysql:host=localhost;dbname=someDatabase', $username, $password); | |
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$stmt = $pdo->prepare('INSERT INTO someTable VALUES(:name)'); | |
$stmt->execute(array( | |
':name' => 'Justin Bieber' | |
)); | |
# Affected Rows? | |
echo $stmt->rowCount(); // 1 | |
} catch(PDOException $e) { | |
echo 'Error: ' . $e->getMessage(); | |
// UPDATE | |
$id = 5; | |
$name = "Joe the Plumber"; | |
try { | |
$pdo = new PDO('mysql:host=localhost;dbname=someDatabase', $username, $password); | |
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$stmt = $pdo->prepare('UPDATE someTable SET name = :name WHERE id = :id'); | |
$stmt->execute(array( | |
':id' => $id, | |
':name' => $name | |
)); | |
echo $stmt->rowCount(); // 1 | |
} catch(PDOException $e) { | |
echo 'Error: ' . $e->getMessage(); | |
// DELETE | |
$id = 5; // From a form or something similar | |
try { | |
$pdo = new PDO('mysql:host=localhost;dbname=someDatabase', $username, $password); | |
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$stmt = $pdo->prepare('DELETE FROM someTable WHERE id = :id'); | |
$stmt->bindParam(':id', $id); // this time, we'll use the bindParam method | |
$stmt->execute(); | |
echo $stmt->rowCount(); // 1 | |
} catch(PDOException $e) { | |
echo 'Error: ' . $e->getMessage(); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment