2 // @title MySQL DB Connection class
3 // @author Matt Todd <matt@matttoddphoto.com>
5 // @desc Used to connect and interact with MySQL databases. Inherits
6 // basic functionality and structure from the DBAbstract class.
8 // include_once 'db.php';
9 // include_once 'stdexception.php';
11 class mysql
extends database
{
12 // defined in the 'database' class
13 // public $config, $handle, $query, $result, $is_connected; // state and configuration
15 // functions to override
16 /* abstract public function connect();
17 abstract public function disconnect();
18 abstract public function select_db($database);
19 abstract public function query($query);
20 abstract public function iterate();
21 abstract public function select($params, $table);
24 // overridden functions
25 public function connect() {
26 // establish connection
27 if(!($this->handle
= @mysql_pconnect
($this->config
['host'], $this->config
['username'], $this->config
['password']))) die(mysql_error()); // throw new DBConnectionException(mysql_errno(), mysql_error(), (__FILE__ . ', line ' . __LINE__));
28 $this->is_connected
= true;
32 public function disconnect() {
33 if(mysql_close($this->db
)) {
34 $this->is_connected
= false;
42 public function select_db($database = null) {
43 if(!empty($database)) $this->config
['database'] = $database; else $database = $this->config
['database'];
44 if($this->is_connected
) {
45 if(!@mysql_select_db
($database, $this->handle
)) throw new CouldNotSelectDB(mysql_errno(), mysql_error(), (__FILE__
. ', line ' . __LINE__
));
48 throw new CouldNotSelectDB("0002", "Not connected to the Database", (__FILE__
. ', line ' . __LINE__
));
52 public function query($query) {
53 $this->query
= $query;
54 // print $query . "<br />\n";
56 @mysql_free_result
($this->result
);
58 Debug
::log("Executed '{$this->query}'", 'sql', 'info', 'MySQL');
61 if(!($this->result
= @mysql_query
($this->query
, $this->db
))) throw new CouldNotIterate(mysql_errno(), mysql_error(), (__FILE__
. ', line ' . __LINE__
));
64 // catch(DBException $e) {
65 // // $this->result = null;
72 public function get_row() {
74 switch($this->row_result_type
) {
75 case "self::ROWRESTYPE_INDEXED":
76 case self
::ROWRESTYPE_INDEXED
:
77 if(!($this->row
= @mysql_fetch_row
($this->result
))) throw new DBException(mysql_errno(), mysql_error(), (__FILE__
. ', line ' . __LINE__
));
81 case "self::ROWRESTYPE_ASSOC":
82 case self
::ROWRESTYPE_ASSOC
:
83 if(!($this->row
= @mysql_fetch_assoc
($this->result
))) throw new DBException(mysql_errno(), mysql_error(), (__FILE__
. ', line ' . __LINE__
));
86 case "self::ROWRESTYPE_OBJECT":
87 case self
::ROWRESTYPE_OBJECT
:
88 if(!($this->row
= @mysql_fetch_object
($this->result
))) throw new DBException(mysql_errno(), mysql_error(), (__FILE__
. ', line ' . __LINE__
));
93 catch(DBException
$e) {
101 public function iterate($result = null) {
102 if($result == null) $result = $this->result
;
104 if(!($this->row
= @mysql_fetch_assoc
($result)) && $this->row
!= false) throw new CouldNotIterate(mysql_errno(), mysql_error(), (__FILE__
. ', line ' . __LINE__
));
105 // print_r($this->row);
108 // catch(DBException $e) {
110 // $this->row = null;
111 // $this->error = $e;
115 public function select($params, $table) {
117 $where_operator = !empty($params["where_operator"]) ?
$params["where_operator"] : "AND";
119 // compile list of columns to select (usually defaults to "*")
120 if(is_array($params["columns"])) {
121 $columns = implode($params["columns"], ", ");
123 // if nothing is specified, select everything
124 $columns = !empty($params["columns"]) ?
$params["columns"] : "*";
127 // compile the list of WHERE arguments
128 if(is_array($params["where"])) {
129 foreach($params["where"] as $column=>$values) {
130 if(is_array($values) && is_int($column)) {
131 // support for passing in arrays of ('key','value')
132 if($where != "") $where .= " {$where_operator} "; // append value of $strWhereOperator
133 $where .= "{$values[0]}='{$values[1]}'";
134 } elseif(is_array($values)) {
135 foreach($values as $value) {
136 if($clause != "") $clause .= " OR ";
137 $clause .= "{$column}='{$value}'";
139 if($where != "") $where .= " {$where_operator} "; // append value of $strWhereOperator
142 if($where != "") $where .= " {$where_operator} "; // append value of $strWhereOperator
143 $where .= "{$column}='{$values}'";
147 if(!empty($params["where"])) $where = $params["where"];
149 if(!empty($where)) $where = "WHERE {$where}";
152 if(!empty($params["order_by"])) $order_by = "ORDER BY " . $params["order_by"];
155 if(!empty($params["limit"])) $limit = "LIMIT " . $params["limit"];
157 // "SELECT {$columns} FROM {$table} {$strWhere}{$strOrderBy};"
158 $query = 'SELECT %s FROM %s %s %s %s;';
161 // print sprintf($query, $columns, $table, $where, $order_by, $limit) . "<br />\n";
164 $this->query(sprintf($query, $columns, $table, $where, $order_by, $limit));
166 public function insert($params, $table) {
167 // get columns of the table
168 $table_columns = $this->explain_table($table);
170 // compile list of columns and values to insert
171 foreach($params as $column=>$value) {
172 // check if it's an association
173 if(is_array($value) ||
is_object($value)) continue;
175 // don't insert 'id' values
176 if($column == "id") continue;
178 // also, don't update if it's not one of the columns in the table (uh, duh)
179 if(!in_array($column, $table_columns)) continue;
182 if(!empty($columns)) $columns .= ', ';
183 if(!empty($values)) $values .= ', ';
185 // add slashes to help prevent SQL Injection problems
186 // $value = addslashes($value);
188 // assemble query strings
189 $columns .= "{$column}";
190 $values .= "'{$value}'";
193 // "INSERT INTO {$table} ({$strColumns}) VALUES ({$values});"
194 $query = 'INSERT INTO %s (%s) VALUES (%s);';
197 // print sprintf($query, $table, $columns, $values);
200 $this->query(sprintf($query, $table, $columns, $values));
202 public function update($params, $table) {
203 // get columns of the table
204 $table_columns = $this->explain_table($table);
206 // compile list of columns and values to insert
207 foreach($params as $column=>$value) {
208 // check if it's an association
209 if(is_array($value) ||
is_object($value)) continue;
211 // don't update 'id' values (in the where clause)
212 if($column == "id") continue;
214 // also, don't update if it's not one of the columns in the table (uh, duh)
215 if(!in_array($column, $table_columns)) continue;
218 if(!empty($columns)) $columns .= ', ';
220 // add slashes to help prevent SQL Injection problems
221 // $value = addslashes($value);
223 // assemble query strings
224 $columns .= "{$column}='{$value}'";
227 // "UPDATE {$table} SET {$columns} WHERE id='{$params[id]}';"
228 $query = 'UPDATE %s SET %s WHERE id=\'%s\';';
231 // print sprintf($query, $table, $columns, $params['id']);
234 $this->query(sprintf($query, $table, $columns, $params['id']));
236 public function delete($params, $table) {
238 $id = empty($params['id']) ?
$params['where']['id'] : $params['id'];
240 // "DELETE FROM {$table} WHERE id='{$nId}';"
241 $query = 'DELETE FROM %s WHERE id=\'%s\' LIMIT 1;';
244 $this->query(sprintf($query, $table, $id));
245 // print "DELETE FROM {$table} WHERE id='{$nId}';";
247 public function delete_all($params, $table) {
249 $where_operator = !empty($params["where_operator"]) ?
$params["where_operator"] : "AND";
251 // compile list of columns to select (usually defaults to "*")
252 if(is_array($params["columns"])) {
253 $columns = implode($params["columns"], ", ");
255 // if nothing is specified, select everything
256 $columns = !empty($params["columns"]) ?
$params["columns"] : "*";
259 // compile the list of WHERE arguments
260 if(is_array($params["where"])) {
261 foreach($params["where"] as $column=>$value) {
262 if($where != "") $where .= " {$where_operator} "; // append value of $strWhereOperator
263 $where .= "{$column}='{$value}'";
266 if(!empty($params["where"])) $where = $params["where"];
268 if(!empty($where)) $where = "WHERE {$where}";
270 if(!empty($params['limit'])) $limit = "LIMIT {$params[limit]}"; // for when in 'delete' // else $limit = "LIMIT 1";
272 // "SELECT {$columns} FROM {$table} {$strWhere}{$strOrderBy};"
273 $query = 'DELETE FROM %s %s %s;';
276 // print sprintf($query, $table, $where, $limit) . "<br />\n";
279 $this->query(sprintf($query, $table, $where, $limit));
283 public function get_last_id() {
284 return mysql_insert_id();
286 public function rows_found() {
287 return mysql_num_rows($this->result
);
289 public function affected_rows() {
290 return mysql_affected_rows($this->db
);
293 // get table column names (to make sure 'updates' and 'inserts' don't try to update a column that doesn't exist)
294 public function explain_table($table) {
296 $query = "EXPLAIN {$table};";
299 $result = @mysql_query
($query, $this->db
);
301 // loop through details
302 while($row = @mysql_fetch_assoc
($result)) {
306 foreach($rows as $column) {
307 $columns[] = $column['Field'];
314 class CouldNotConnect
extends StdException
{ }
315 class CouldNotSelectDB
extends StdException
{ }
316 class CouldNotIterate
extends StdException
{ }
317 class CouldNotFind
extends StdException
{ }
318 class CouldNotSave
extends StdException
{ }
319 class CouldNotDelete
extends StdException
{ }