Created
March 10, 2012 21:19
-
-
Save stefanledin/2013236 to your computer and use it in GitHub Desktop.
CRUD med PDO - En lathund
This file contains hidden or 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 | |
| /** | |
| * 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