Created
July 23, 2015 11:33
-
-
Save lnaia/84e4b3964b757575d355 to your computer and use it in GitHub Desktop.
php pdo example
This file contains 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 | |
define("DB_DSN", "mysql:host=localhost;dbname=DATABASE_NAME_GOES_HERE"); | |
define("DB_USERNAME", ""); | |
define("DB_PASSWORD", ""); | |
// Example usage | |
function mysql_custom_query() | |
{ | |
$name = "xpto"; | |
$query = "SELECT * FROM Users where name = :XXX_USER_XXX"; | |
$special_values = array( | |
array( | |
'key' => "XXX_USER_XXX", | |
'value' => $name, | |
'kind' => PDO::PARAM_STR | |
), | |
); | |
$results = queryDB($query, $special_values); | |
echo "<pre>"; | |
var_dump($results); | |
echo "</pre>"; | |
} | |
/** | |
* @param $query | |
* @param array $parameters | |
* @return array | |
* | |
* For more constant values check in the parameters array check: | |
* http://php.net/manual/en/pdo.constants.php | |
* | |
* For more information about the bind: | |
* http://php.net/manual/en/pdostatement.bindparam.php | |
*/ | |
function queryDB($query, $parameters = array()) | |
{ | |
try { | |
$pdo = new PDO( | |
DB_DSN, | |
DB_USERNAME, | |
DB_PASSWORD | |
); | |
$preparedStatement = $pdo->prepare($query); | |
foreach ($parameters as $item) { | |
$preparedStatement->bindParam( | |
$item['key'], | |
$item['value'], | |
$item['kind'] | |
); | |
} | |
return [ | |
'status' => $preparedStatement->execute(), | |
'results' => $preparedStatement->fetchAll(), | |
]; | |
} catch (Exception $e) { | |
// no sql exceptions or errors should ever go to the end user | |
// modify this at your own risk | |
error_log($e->getMessage()); | |
error_log($e->getTraceAsString()); | |
exit(1); | |
} | |
} | |
mysql_custom_query(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment