base bazdig.db vide
[bazdig.git] / lib / code.php
blob0e2a5b3bbbbdcc52f1f37a6d07271ccfda7274aa
1 <?php
3 require_once "persistance.php";
4 require_once "database.php";
6 class SqlCode implements sql, persistance
8 static $db;
9 var $id;
10 var $code;
11 var $date;
13 function __construct($code)
15 $this->code = $code;
16 $this->date = date('c');
17 $this->id = 'md5:'. md5($this->code);
20 public static function get_table_name()
22 return "sql";
25 public static function sql_select($options = NULL)
27 $table = self::get_table_name();
28 $query = "select id, code, date from $table $options";
29 return $query;
32 function toSQLselect()
34 $table = $this->get_table_name();
35 $id = $this->id;
36 $query = "select id, code, date from $table where id='$id'";
37 return $query;
40 function toSQLinsert()
42 $table = $this->get_table_name();
43 $id = $this->id;
44 $code = str_replace("'", "''",$this->code);
45 $date = $this->date;
46 $query = "insert into $table (id, code, date) values ('$id', '$code', '$date')";
47 return $query;
50 static function set_db($db)
52 if ($db instanceof PDO) {
53 self::$db =& $db;
54 } else {
55 if (empty($user)) {
56 self::$db =& new PDO($db);
57 } else {
58 self::$db =& new PDO($db, $user, $password);
61 self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
63 return self::$db;
66 static function select($options = NULL, $db = NULL)
68 if (!$db) $db =& self::$db;
69 $query = self::sql_select($options);
70 $result = $db->query($query);
71 $scripts = array();
72 foreach ($result as $r) {
73 $s = new SqlCode($r['code']);
74 $s->id = $r['id'];
75 $s->date = $r['date'];
76 $scripts []= $s;
78 return $scripts;
81 function save($db = NULL)
83 if (!$db) $db =& self::$db;
84 $query = $this->toSQLinsert();
85 $id = $this->id;
86 $table = self::get_table_name();
87 try {
88 $db->exec($query);
89 } catch (PDOException $e) {
90 if ($db->errorCode() == "23000") { // l'id existe dans la table
91 $db->exec("delete from $table where id='$id'");
92 $db->exec($query);
93 } else {
94 die($e->getMessage());
97 return $this;
100 static function search($string, $options = NULL)
102 $options = str_replace("where", "and", $options);
103 $scripts = self::select("where code like '%$string%' $options");
104 return $scripts;
107 function exec($db)
109 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
110 $result = $db->query($this->code);
111 return $result;
114 function extractColumns()
116 eregi('create +table +[^(]+\(([^)]+)', $this->code, $strings);
117 $columns = split(',', $strings[1]);
118 for ($i=0; $i < count($columns); $i++) {
119 $c = new Column(firstWord($columns[$i]));
120 $columns[$i] = $c;
122 return $columns;