Created
May 16, 2015 01:16
-
-
Save ibourgeois/eb96708d361aaca90f1d to your computer and use it in GitHub Desktop.
PDO Example
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 | |
require 'db.php'; | |
if (!empty($_POST)): | |
$data = array( | |
'firstname' => $_POST['firstname'], | |
'lastname' => $_POST['lastname'], | |
'email' => $_POST['email'] | |
); | |
return create($data); | |
else: ?> | |
<form <?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="POST"> | |
<input type="text" name="firstname" /> | |
<input type="text" name="lastname" /> | |
<input type="email" name="email" /> | |
<input type="submit" value="Save" /> | |
</form> | |
<?php endif; ?> |
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 | |
function create($data) { | |
$host = "localhost"; | |
$user = "username"; | |
$pass = "password"; | |
$name = "table"; | |
try { | |
$db = new PDO("mysql:host=$host;dbname=$name", $user, $pass); | |
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$query = $db->prepare("INSERT INTO users (firstname, lastname, email) | |
VALUES (:firstname, :lastname, :email)"); | |
$query->bindParam(':firstname', $first); | |
$query->bindParam(':lastname', $last); | |
$query->bindParam(':email', $email); | |
$first = $data['firstname']; | |
$last = $data['lastname']; | |
$email = $data['email']; | |
$query->execute(); | |
} | |
catch(PDOException $error) { | |
return "Error: " . $error->getMessage(); | |
} | |
} | |
function getUsers() { | |
$host = "localhost"; | |
$user = "username"; | |
$pass = "password"; | |
$name = "table"; | |
try { | |
$db = new PDO("mysql:host=$host;dbname=$name", $user, $pass); | |
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$query = $db->prepare("SELECT * FROM users"); | |
$query->execute(); | |
return $query->fetchAll(); | |
} | |
catch(PDOException $error) { | |
return "Error: " . $error->getMessage(); | |
} | |
} |
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 | |
require 'db.php'; | |
$users = getUsers(); | |
?> | |
<ul> | |
<?php foreach ($users as $user) { ?> | |
<li><?php echo $user['firstname']; ?> <?php echo $user['lastname']; ?> <b>(<?php echo $user['email']; ?>)</b></li> | |
<?php } ?> | |
</ul> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment