Skip to content

Instantly share code, notes, and snippets.

@magnusbonnevier
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magnusbonnevier/37e544706065a55b008d to your computer and use it in GitHub Desktop.
Save magnusbonnevier/37e544706065a55b008d to your computer and use it in GitHub Desktop.
PHP PDO reference gists. Mainly for my own use but anyone is welcome to fork and use it.
<?php
/*
Example copied from:
http://php.net/manual/en/pdo.prepared-statements.php
I altered it slightly to my taste of coding.
*/
// insert one row of data contained in these vars
$name = 'one';
$value = 1;
// Prepare the SQL query using named substitution.
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
// bind the vars to the substitued named placeholders
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// execute the query
$stmt->execute();
?>
<?php
/*
Example from:
http://php.net/manual/en/pdo.connections.php
In the PDO() method the parameters are as follows:
host = hostname of the database server
dbname = the name of the database you want to connect to.
$user = username
$pass = password
Misc:
$dbh = variable where we store our database handler that is returned.
This we can use to perform different operations like CRUD.
C = Create
R = Read
U = Update
D = Delete
Like Querys and INSERT, UPDATE, DELETE, SELECT and so on.
*/
try {
// Try to make a connection
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// close the connection
$dbh = null;
} catch (PDOException $e) {
// If connection fails then catch it and display error
print "Error!: " . $e->getMessage() . "<br/>";
// kill the script because we dont want anything else after to run.
die();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment