Skip to content

Instantly share code, notes, and snippets.

@tractorcow
Created September 4, 2017 22:27
Show Gist options
  • Save tractorcow/390c9075020b6e2fdfa807c835403afa to your computer and use it in GitHub Desktop.
Save tractorcow/390c9075020b6e2fdfa807c835403afa to your computer and use it in GitHub Desktop.
Proof of flakey DB connector
<?php
ini_set('log_errors', 0);
ini_set('display_errors', 1);
$options = [
PDO::ATTR_EMULATE_PREPARES => false
];
global $connection;
$connection = new PDO(
"mysql:host=127.0.0.1;charset=utf8",
getenv("SS_DATABASE_USERNAME"),
getenv("SS_DATABASE_PASSWORD"),
$options
);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function message($message)
{
echo "$message\n";
}
function prepared($sql, $args)
{
message("running $sql");
global $connection;
$statement = $connection->prepare(
$sql,
array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)
);
if (!$statement) {
throw new Exception("Failed prepare: $sql");
}
$statement->execute($args);
$result = $statement->fetchAll();
$statement->closeCursor();
message("closing cursor");
return $result;
};
function query($sql)
{
return prepared($sql, []);
};
// Will error with:
// SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other
// unbuffered queries are active. Consider using PDOStatement::fetchAll().
// Alternatively, if your code is only ever going to run against mysql, you
// may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.
query('USE SS_ss40dev');
foreach (prepared('SELECT * FROM "SiteTree" WHERE "ID" = ?', [1]) as $row) {
var_dump($row);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment