Skip to content

Instantly share code, notes, and snippets.

@stefanledin
Created March 10, 2012 21:19
Show Gist options
  • Select an option

  • Save stefanledin/2013236 to your computer and use it in GitHub Desktop.

Select an option

Save stefanledin/2013236 to your computer and use it in GitHub Desktop.
CRUD med PDO - En lathund
<?php
/**
* CRUD med PDO - en lathund
* Av: Stefan Ledin
* stefanledin.se
* @stefanledin
*/
try {
/**
* Ansluta
*/
$pdo = new PDO('mysql:host=localhost;dbname=database','root','root');
/**
* Förbered databasfråga och verkställ
*/
$stmt = $pdo->prepare('
SELECT firstname, lastname
FROM pdo
');
$stmt->execute();
/**
* Hämta resultat, variant #1
*/
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<pre>';
print_r($result);
echo '</pre>';
}
/**
* Hämta resultat, variant #2
*/
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $player) {
echo '<li>'.$player->firstname.' '.$player->lastname.'</li>';
}
/**
* Skapa
*/
$stmt = $pdo->prepare('
INSERT INTO pdo (firstname, lastname)
VALUES (:firstname, :lastname)
');
$firstname = 'Ilya';
$lastname = 'Kovalchuck';
$stmt->execute(array(':firstname' => $firstname, ':lastname' => $lastname));
/**
* Redigera
*/
$stmt = $pdo->prepare('
UPDATE pdo
SET club = :club
WHERE id = :id
');
$club = 'New Jersey Devils';
$id = '8';
$stmt->execute(array(':club' => $club, ':id' => $id));
/**
* Radera
*/
$stmt = $pdo->prepare('
DELETE FROM pdo
WHERE id = :id
');
$id = 8;
$stmt->execute(array(':id' => $id));
/**
* Stäng anslutningen
*/
$pdo = null;
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment