From 63c0cf521f8097b0dadaf1228176dc38c7d897f6 Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Thu, 15 May 2014 18:28:24 +0200 Subject: Working on config.tgz composition through config modules --- inc/database.inc.php | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 inc/database.inc.php (limited to 'inc/database.inc.php') diff --git a/inc/database.inc.php b/inc/database.inc.php new file mode 100644 index 00000000..70f50116 --- /dev/null +++ b/inc/database.inc.php @@ -0,0 +1,92 @@ + "SET NAMES utf8")); + } catch (PDOException $e) { + Util::traceError('Connecting to the local database failed: ' . $e->getMessage()); + } + } + + /** + * If you just need the first row of a query you can use this. + * Will return an associative array, or false if no row matches the query + */ + public static function queryFirst($query, $args = array()) + { + $res = self::simpleQuery($query, $args); + if ($res === false) return false; + return $res->fetch(PDO::FETCH_ASSOC); + } + + /** + * Execute the given query and return the number of rows affected. + * Mostly useful for UPDATEs or INSERTs + */ + public static function exec($query, $args = array()) + { + $res = self::simpleQuery($query, $args); + if ($res === false) return false; + return $res->rowCount(); + } + + /** + * Get id (promary key) of last row inserted. + * + * @return int the id + */ + public static function lastInsertId() + { + return self::$dbh->lastInsertId(); + } + + /** + * Execute the given query and return the corresponding PDOStatement object + * Note that this will re-use PDOStatements, so if you run the same + * query again with different params, do not rely on the first PDOStatement + * still being valid. If you need to do something fancy, use Database::prepare + */ + public static function simpleQuery($query, $args = array()) + { + self::init(); + try { + if (!isset(self::$statements[$query])) { + self::$statements[$query] = self::$dbh->prepare($query); + } else { + self::$statements[$query]->closeCursor(); + } + if (self::$statements[$query]->execute($args) === false) { + Util::traceError("Database Error: \n" . implode("\n", self::$statements[$query]->errorInfo())); + } + return self::$statements[$query]; + } catch (Exception $e) { + return false; + } + } + + /** + * Simply calls PDO::prepare and returns the PDOStatement. + * You must call PDOStatement::execute manually on it. + */ + public static function prepare($query) + { + self:init(); + return self::$dbh->prepare($query); + } + +} + -- cgit v1.2.3-55-g7522