Last active
August 29, 2015 13:57
-
-
Save bbatsche/9611256 to your computer and use it in GitHub Desktop.
Examples of PDO Calls
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 | |
/******************************* | |
* Setup Connection | |
*******************************/ | |
$dbc = new PDO('mysql:host=127.0.0.1;dbname=codeup_demo_db', 'username', 'password'); | |
// Tell PDO to throw exceptions on error | |
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
/******************************* | |
* Execute | |
*******************************/ | |
$numRows = $dbc->exec("INSERT IGNORE INTO user (username, first_name, last_name) | |
VALUES ('bbatschelet', 'Ben', 'Batschelet')"); | |
/******************************* | |
* Last Insert ID | |
*******************************/ | |
$dbc->lastInsertId(); | |
/******************************* | |
* Query | |
*******************************/ | |
$result = $dbc->query('SELECT * FROM user LIMIT 10'); | |
$result->columnCount(); | |
$result->rowCount(); | |
/******************************* | |
* Fetch | |
*******************************/ | |
/* | |
* http://www.php.net/manual/en/pdostatement.fetch.php | |
* PDO::FETCH_BOTH | |
* PDO::FETCH_ASSOC | |
* PDO::FETCH_NUM | |
*/ | |
while ($row = $result->fetch(PDO::FETCH_ASSOC)) { | |
print_r($row); | |
} | |
// OR... | |
$rows = $result->fetchAll(); | |
/******************************* | |
* Prepared Statement | |
*******************************/ | |
$insert = $dbc->prepare('INSERT INTO user (username, first_name, last_name) VALUES(?, ?, ?)'); | |
$insert->execute(array('icastillo', 'Isaac', 'Castillo')); | |
$insert = $dbc->prepare('INSERT INTO user (username, first_name, last_name) VALUES(:username, :firstName, :lastName)'); | |
/******************************* | |
* Bind Value | |
*******************************/ | |
/* | |
* http://www.php.net/manual/en/pdo.constants.php | |
* PDO::PARAM_BOOL | |
* PDO::PARAM_NULL | |
* PDO::PARAM_INT | |
* PDO::PARAM_STR | |
*/ | |
$insert->bindValue(':username', $var['jstraughn'], PDO::PARAM_STR); | |
$insert->bindValue(':firstName', $var['Jason'], PDO::PARAM_STR); | |
$insert->bindValue(':lastName', $var['Straughn'], PDO::PARAM_STR); | |
$insert->execute(); | |
?> | |
<a href="?remove=<?= $row['id']?>">Remove!</a> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment