Recursively search for database config
[infodrom.org/service.infodrom.org] / class / databasetable.class.php
1 <?php
2
3 abstract class DatabaseTable {
4   protected $idcolumn = 'id';
5   protected $db;
6   protected $table;
7   protected $data;
8   protected $id;
9
10   public function __construct($table, $id=false, $column_or_db=false, $column=false)
11   {
12     global $db;
13
14     $this->table = $table;
15
16     if ($column_or_db && is_object($column_or_db)) {
17       $this->db = $column_or_db;
18       $col = $column;
19     } else {
20       $this->db = $db;
21       $col = $column_or_db;
22     }
23
24     if ($id && !$col) $this->load($id);
25     if ($id && $col) $this->loadByColumn($id,$col);
26   }
27
28   protected function postLoad() {}
29
30   protected function load($id)
31   {
32     $sql = sprintf("SELECT * FROM %s WHERE %s = %d LIMIT 1",
33                    $this->table, $this->idcolumn, $id);
34     $this->data = $this->db->fetchObject($sql);
35     if ($this->data) {
36       $idcolumn = $this->idcolumn;
37       $this->id = $this->data->$idcolumn;
38       $this->postLoad();
39       return true;
40     }
41     return false;
42   }
43
44   protected function loadByColumn($id,$column)
45   {
46     $sql = sprintf("SELECT * FROM %s WHERE %s = %s",
47            $this->table, $column, $this->db->quote($id));
48     $this->data = $this->db->fetchObject($sql);
49     if ($this->data) {
50       $idcolumn = $this->idcolumn;
51       $this->id = $this->data->$idcolumn;
52       $this->postLoad();
53     }
54   }
55
56   public function id()
57   {
58     return $this->id;
59   }
60
61   public function fetch()
62   {
63     return $this->data;
64   }
65
66   public function modify($column, $value=false, $id=false)
67   {
68     if (!is_array($column) && $value !== false)
69       $column = array($column => $value);
70     elseif (!is_array($column) || $value !== false)
71       throw Exception('modify called with wrong parameters');
72
73     if ($this->db->update($this->table, $column, $this->idcolumn.'='.($id === false ? $this->id : $id)))
74       return $id === false ? $this->load($this->id) : true;
75     else
76       return false;
77   }
78
79   public function delete($id=false)
80   {
81     $this->db->delete($this->table, $this->idcolumn, $id === false ? $this->id : $id);
82   }
83
84 }
85
86 ?>