Cheatography
https://cheatography.com
Connexion
try {
$conn = new PDO('mysql:host=[SERVEUR];dbname=[BASE]', "[IDENTIFIANT]", "[MOT DE PASSE]");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
|
Select résultat unique
$id = 5;
try {
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
|
Select résultat multiple
$id = 5;
try {
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
print_r($row);
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
|
Insert
try {
$stmt = $pdo->prepare('INSERT INTO someTable VALUES(:name)');
$stmt->bindParam(':name', 'Justin Bieber', PDO::PARAM_STR);
$stmt->execute();
# Affected Rows?
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
|
Update
$id = 5;
$name = "Joe the Plumber";
try {
$stmt = $pdo->prepare('UPDATE someTable SET name = :name WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
|
Delete
$id = 5;
try {
$stmt = $pdo->prepare('DELETE FROM someTable WHERE id = :id');
$stmt->bindParam(':id', $id);
$stmt->execute();
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
|
|
Created By
arnaud-ritti.fr
Metadata
Favourited By
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets