From 8888c6a2a620fa8862f20a0dcca01ad474c66cd2 Mon Sep 17 00:00:00 2001 From: Josh Sherman Date: Thu, 19 Jun 2008 01:01:43 +0000 Subject: [PATCH] Added the update method for easier updates w/o SQL. git-svn-id: http://svn.cleancode.org/svn/pickles@21 4d10bc64-7434-11dc-a737-d2d0f8310089 --- classes/DB.php | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/classes/DB.php b/classes/DB.php index 6e492fa..97154ef 100755 --- a/classes/DB.php +++ b/classes/DB.php @@ -172,7 +172,49 @@ class DB { } public static function update($table, $columnValues, $conditions) { + if (!is_resource(self::$connection)) { + self::open(); + } + if (trim($table) != '') { + // @todo Check that the table exists, and possibly check that the columns exist as well + + $fields = $where = null; + if (is_array($columnValues)) { + foreach ($columnValues as $key => $value) { + $fields .= ($fields ? ', ' : null) . $key . " = '" . mysql_real_escape_string(stripslashes($value), self::$connection) . "'"; + } + + if (is_array($conditions)) { + foreach ($conditions as $key => $value) { + $where = ($where == null) ? 'WHERE ' : ' AND '; + + if ($value == null) { + $where .= $key . ' IS NULL'; + } + else { + $where .= $key . " = '" . mysql_real_escape_string(stripslashes($value), self::$connection) . "'"; + } + } + + $sql = 'UPDATE ' . $table . ' SET ' . $fields . $where; + if (self::execute($sql)) { + return true; + } + } + else { + Error::addError('No conditions were specified'); + } + } + else { + Error::addError('No data was specified'); + } + } + else { + Error::addError('No database table was specified'); + } + + return false; } public static function delete($table, $columnValues, $conditions) {