classe BDB et sa methode listTables()
[bazdig.git] / lib / code.php
blobd4aaa64df1392d9fe321918058d44284e5c1abbd
1 <?php
3 require "persistance.php";
5 class SqlCode implements sql, persistance
7 static $db;
8 var $id;
9 var $code;
10 var $date;
12 function __construct($code)
14 $this->code = $code;
15 $this->date = date('c');
16 $this->id = 'md5:'. md5($this->code);
19 public static function get_table_name()
21 return "sql";
24 public static function sql_select($options = NULL)
26 $table = self::get_table_name();
27 $query = "select id, code, date from $table $options";
28 return $query;
31 function toSQLselect()
33 $table = $this->get_table_name();
34 $id = $this->id;
35 $query = "select id, code, date from $table where id='$id'";
36 return $query;
39 function toSQLinsert()
41 $table = $this->get_table_name();
42 $id = $this->id;
43 $code = str_replace("'", "''",$this->code);
44 $date = $this->date;
45 $query = "insert into $table (id, code, date) values ('$id', '$code', '$date')";
46 return $query;
49 static function set_db($db)
51 if ($db instanceof PDO) {
52 self::$db =& $db;
53 } else {
54 if (empty($user)) {
55 self::$db =& new PDO($db);
56 } else {
57 self::$db =& new PDO($db, $user, $password);
60 self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
62 return self::$db;
65 static function select($options = NULL, $db = NULL)
67 if (!$db) $db =& self::$db;
68 $query = self::sql_select($options);
69 $result = $db->query($query);
70 $scripts = array();
71 foreach ($result as $r) {
72 $s = new SqlCode($r['code']);
73 $s->id = $r['id'];
74 $s->date = $r['date'];
75 $scripts []= $s;
77 return $scripts;
80 function save($db = NULL)
82 if (!$db) $db =& self::$db;
83 $query = $this->toSQLinsert();
84 $id = $this->id;
85 $table = self::get_table_name();
86 try {
87 $db->exec($query);
88 } catch (PDOException $e) {
89 if ($db->errorCode() == "23000") { // l'id existe dans la table
90 $db->exec("delete from $table where id='$id'");
91 $db->exec($query);
92 } else {
93 die($e->getMessage());
96 return $this;
99 static function search($string, $options = NULL)
101 $options = str_replace("where", "and", $options);
102 $scripts = self::select("where code like '%$string%' $options");
103 return $scripts;
106 function exec($db)
108 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
109 $result = $db->query($this->code);
110 return $result;