From 12b1b6ecf7c8cc0e6ff418443787d7c247aa413a Mon Sep 17 00:00:00 2001 From: Remi Collet Date: Wed, 9 Jun 2010 01:24:25 +0800 Subject: add CommonTable->delete() method --- class/CommonTable.php | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/class/CommonTable.php b/class/CommonTable.php index 1ed47f8..261c7aa 100644 --- a/class/CommonTable.php +++ b/class/CommonTable.php @@ -73,6 +73,8 @@ abstract class CommonTable * Execute an SQL statement (INSERT, DELETE, ...) * * @param string $sql The SQL clause + * + * @param integer number of affected rows */ protected function exec($sql) { @@ -81,14 +83,17 @@ abstract class CommonTable $err = $this->db->errorInfo(); throw new Exception($err[2]); } + return $res; } /** * Add a new row in the table * * @param hashtable $fields hashtable of fieldname => value + * + * @return integer primary key of inserted row */ - protected function add(array $fields) + public function add(array $fields) { $col = array(); $val = array(); @@ -99,14 +104,47 @@ abstract class CommonTable } else if (is_numeric($value)) { $val[] = $value; } else { - $val[] = "'$value'"; + $val[] = "'".addslashes($value)."'"; } } $sql = "INSERT INTO `".$this->table."` (".implode(',', $col).") VALUE (".implode(',', $val).")"; $this->exec($sql); + + $id = $this->db->lastInsertId(); + + return $id; } + /** + * Delete a row in the table + * + * @param hashtable $crit of key => value + * + * @return integer : number of row deleted + */ + public function delete(array $crit) + { + $sql = "DELETE FROM `".$this->table."` "; + + $link="WHERE"; + foreach ($crit as $key => $value) { + $sql .= " $link `$key`"; + + if (is_null($value)) { + $sql .= 'IS NULL'; + } else if (is_numeric($value)) { + $sql .= '='.$value; + } else { + $sql .= "='".addslashes($value)."'"; + } + + $link = "AND"; + } + $nb = $this->exec($sql); + + return $nb; + } /** * Create the table */ -- cgit