root/alternc/trunk/bureau/class/db_mysql.php

Revision 1713, 12.0 kB (checked in by nahuel, 2 years ago)

On n'affiche pas les erreurs mysql qui font planter si la bdd existe déjà
Closes: #698

Line 
1 <?php
2
3 /**
4  * Session Management for PHP3
5  *
6  * Copyright (c) 1998-2000 NetUSE AG
7  *                    Boris Erdmann, Kristian Koehntopp
8  *
9  * $Id: db_mysql.php,v 1.3 2005/03/05 16:27:30 said Exp $
10  *
11  */
12
13 class DB_Sql {
14  
15   /* public: connection parameters */
16   var $Host     = "";
17   var $Database = "";
18   var $User     = "";
19   var $Password = "";
20
21   /* public: configuration parameters */
22   var $Auto_Free     = 0;     ## Set to 1 for automatic mysql_free_result()
23   var $Debug         = 0;     ## Set to 1 for debugging messages.
24   var $Halt_On_Error = "no"; ## "yes" (halt with message), "no" (ignore errors quietly), "report" (ignore errror, but spit a warning)
25   var $Seq_Table     = "db_sequence";
26
27   /* public: result array and current row number */
28   var $Record   = array();
29   var $Row;
30
31   /* public: current error number and error text */
32   var $Errno    = 0;
33   var $Error    = "";
34
35   /* public: this is an api revision, not a CVS revision. */
36   var $type     = "mysql";
37   var $revision = "1.2";
38
39   /* private: link and query handles */
40   var $Link_ID  = 0;
41   var $Query_ID = 0;
42  
43
44
45   /**
46   * Constructor
47   */
48   function DB_Sql($query = "") {
49       $this->query($query);
50   }
51
52   /**
53   * @return the class variable Link_ID
54   */
55   function link_id() {
56     return $this->Link_ID;
57   }
58
59   /**
60   * @return the class variable Query_ID
61   */
62   function query_id() {
63     return $this->Query_ID;
64   }
65
66   /**
67   * function for MySQL database connection management
68   *
69   * This function manages the connection to the MySQL database.
70   *
71   * @param $Database name of the database
72   * @param $Host DNS of the MySQL hosting server
73   * @param $User the user's name
74   * @param $Password the user's password
75   *
76   * @return the class variable $Link_ID
77   */
78   function connect($Database = "", $Host = "", $User = "", $Password = "") {
79     /* Handle defaults */
80     if ("" == $Database)
81       $Database = $this->Database;
82     if ("" == $Host)
83       $Host     = $this->Host;
84     if ("" == $User)
85       $User     = $this->User;
86     if ("" == $Password)
87       $Password = $this->Password;
88       
89     /* establish connection, select database */
90     if ( 0 == $this->Link_ID ) {
91     
92       $this->Link_ID=mysql_pconnect($Host, $User, $Password);
93       if (!$this->Link_ID) {
94         $this->halt("pconnect($Host, $User, \$Password) failed.");
95         return 0;
96       }
97
98       if (!@mysql_select_db($Database,$this->Link_ID)) {
99         $this->halt("cannot use database ".$this->Database);
100         return 0;
101       }
102     }
103     
104     return $this->Link_ID;
105   }
106
107   /**
108   * Discard the query result
109   *
110   * This function discards the last query result.
111   */
112   function free() {
113       @mysql_free_result($this->Query_ID);
114       $this->Query_ID = 0;
115   }
116
117   /**
118   * Perform a query
119   *
120   * This function performs the MySQL query described in the string parameter
121   *
122   * @param a string describing the MySQL query   
123   * @return the $Query_ID class variable (null if fails)
124   */
125   function query($Query_String) {
126     /* No empty queries, please, since PHP4 chokes on them. */
127     if ($Query_String == "")
128       /* The empty query string is passed on from the constructor,
129        * when calling the class without a query, e.g. in situations
130        * like these: '$db = new DB_Sql_Subclass;'
131        */
132       return 0;
133
134     if (!$this->connect()) {
135       return 0; /* we already complained in connect() about that. */
136     };
137
138     # New query, discard previous result.
139     if ($this->Query_ID) {
140       $this->free();
141     }
142
143     if ($this->Debug)
144       printf("Debug: query = %s<br />\n", $Query_String);
145
146     $this->Query_ID = @mysql_query($Query_String,$this->Link_ID);
147     $this->Row   = 0;
148     $this->Errno = mysql_errno();
149     $this->Error = mysql_error();
150     if (!$this->Query_ID) {
151       $this->halt("Invalid SQL: ".$Query_String);
152     }
153
154     # Will return nada if it fails. That's fine.
155     return $this->Query_ID;
156   }
157
158   /**
159   * walk result set
160   *
161   * This function tests if a new record is available in the current
162   * query result.
163   *
164   * @return TRUE if a new record is available
165   */
166   function next_record() {
167     if (!$this->Query_ID) {
168       $this->halt("next_record called with no query pending.");
169       return 0;
170     }
171
172     $this->Record = @mysql_fetch_array($this->Query_ID);
173     $this->Row   += 1;
174     $this->Errno  = mysql_errno();
175     $this->Error  = mysql_error();
176
177     $stat = is_array($this->Record);
178     if (!$stat && $this->Auto_Free) {
179       $this->free();
180     }
181     return $stat;
182   }
183
184   /**
185   *
186   * public: position in result set
187   */
188
189   function seek($pos = 0) {
190     $status = @mysql_data_seek($this->Query_ID, $pos);
191     if ($status)
192       $this->Row = $pos;
193     else {
194       $this->halt("seek($pos) failed: result has ".$this->num_rows()." rows");
195
196       /* half assed attempt to save the day,
197        * but do not consider this documented or even
198        * desireable behaviour.
199        */
200       @mysql_data_seek($this->Query_ID, $this->num_rows());
201       $this->Row = $this->num_rows;
202       return 0;
203     }
204
205     return 1;
206   }
207
208   /* public: table locking */
209   function lock($table, $mode="write") {
210     $this->connect();
211     
212     $query="lock tables ";
213     if (is_array($table)) {
214       while (list($key,$value)=each($table)) {
215         if ($key=="read" && $key!=0) {
216           $query.="$value read, ";
217         } else {
218           $query.="$value $mode, ";
219         }
220       }
221       $query=substr($query,0,-2);
222     } else {
223       $query.="$table $mode";
224     }
225     $res = @mysql_query($query, $this->Link_ID);
226     if (!$res) {
227       $this->halt("lock($table, $mode) failed.");
228       return 0;
229     }
230     return $res;
231   }
232  
233   function unlock() {
234     $this->connect();
235
236     $res = @mysql_query("unlock tables", $this->Link_ID);
237     if (!$res) {
238       $this->halt("unlock() failed.");
239       return 0;
240     }
241     return $res;
242   }
243
244
245   /* public: evaluate the result (size, width) */
246   function affected_rows() {
247     return @mysql_affected_rows($this->Link_ID);
248   }
249
250   function num_rows() {
251     return @mysql_num_rows($this->Query_ID);
252   }
253
254   function num_fields() {
255     return @mysql_num_fields($this->Query_ID);
256   }
257
258   /* public: shorthand notation */
259   function nf() {
260     return $this->num_rows();
261   }
262
263   function np() {
264     print $this->num_rows();
265   }
266
267   function f($Name) {
268     return $this->Record[$Name];
269   }
270
271   function p($Name) {
272     print $this->Record[$Name];
273   }
274
275   function lastid() {
276       return @mysql_insert_id($this->Link_ID);
277   }
278
279   /* public: sequence numbers */
280   function nextid($seq_name) {
281     $this->connect();
282
283     if ($this->lock($this->Seq_Table)) {
284       /* get sequence number (locked) and increment */
285       $q  = sprintf("select nextid from %s where seq_name = '%s'",
286                 $this->Seq_Table,
287                 $seq_name);
288       $id  = @mysql_query($q, $this->Link_ID);
289       $res = @mysql_fetch_array($id);
290       
291       /* No current value, make one */
292       if (!is_array($res)) {
293         $currentid = 0;
294         $q = sprintf("insert into %s values('%s', %s)",
295                  $this->Seq_Table,
296                  $seq_name,
297                  $currentid);
298         $id = @mysql_query($q, $this->Link_ID);
299       } else {
300         $currentid = $res["nextid"];
301       }
302       $nextid = $currentid + 1;
303       $q = sprintf("update %s set nextid = '%s' where seq_name = '%s'",
304                $this->Seq_Table,
305                $nextid,
306                $seq_name);
307       $id = @mysql_query($q, $this->Link_ID);
308       $this->unlock();
309     } else {
310       $this->halt("cannot lock ".$this->Seq_Table." - has it been created?");
311       return 0;
312     }
313     return $nextid;
314   }
315
316   /* public: return table metadata */
317   function metadata($table='',$full=false) {
318     $count = 0;
319     $id    = 0;
320     $res   = array();
321
322     /*
323      * Due to compatibility problems with Table we changed the behavior
324      * of metadata();
325      * depending on $full, metadata returns the following values:
326      *
327      * - full is false (default):
328      * $result[]:
329      *   [0]["table"]  table name
330      *   [0]["name"]   field name
331      *   [0]["type"]   field type
332      *   [0]["len"]    field length
333      *   [0]["flags"]  field flags
334      *
335      * - full is true
336      * $result[]:
337      *   ["num_fields"] number of metadata records
338      *   [0]["table"]  table name
339      *   [0]["name"]   field name
340      *   [0]["type"]   field type
341      *   [0]["len"]    field length
342      *   [0]["flags"]  field flags
343      *   ["meta"][field name]  index of field named "field name"
344      *   The last one is used, if you have a field name, but no index.
345      *   Test:  if (isset($result['meta']['myfield'])) { ...
346      */
347
348     // if no $table specified, assume that we are working with a query
349     // result
350     if ($table) {
351       $this->connect();
352       $id = @mysql_list_fields($this->Database, $table);
353       if (!$id)
354         $this->halt("Metadata query failed.");
355     } else {
356       $id = $this->Query_ID;
357       if (!$id)
358         $this->halt("No query specified.");
359     }
360  
361     $count = @mysql_num_fields($id);
362
363     // made this IF due to performance (one if is faster than $count if's)
364     if (!$full) {
365       for ($i=0; $i<$count; $i++) {
366         $res[$i]["table"] = @mysql_field_table ($id, $i);
367         $res[$i]["name"]  = @mysql_field_name  ($id, $i);
368         $res[$i]["type"]  = @mysql_field_type  ($id, $i);
369         $res[$i]["len"]   = @mysql_field_len   ($id, $i);
370         $res[$i]["flags"] = @mysql_field_flags ($id, $i);
371       }
372     } else { // full
373       $res["num_fields"]= $count;
374     
375       for ($i=0; $i<$count; $i++) {
376         $res[$i]["table"] = @mysql_field_table ($id, $i);
377         $res[$i]["name"]  = @mysql_field_name  ($id, $i);
378         $res[$i]["type"]  = @mysql_field_type  ($id, $i);
379         $res[$i]["len"]   = @mysql_field_len   ($id, $i);
380         $res[$i]["flags"] = @mysql_field_flags ($id, $i);
381         $res["meta"][$res[$i]["name"]] = $i;
382       }
383     }
384
385     // free the result only if we were called on a table
386     if ($table) @mysql_free_result($id);
387     return $res;
388   }
389
390 /********************************************************************************************************/
391 // AJOUT PERSO : TEST
392
393 /* public: return table metadata
394   function retourneNameField($this->Query_ID,$full=false) {
395     $count = 0;
396     $id    = 0;
397     $res   = array();
398
399     
400     $count = @mysql_num_fields($this->Query_ID);
401
402     // made this IF due to performance (one if is faster than $count if's)
403     if (!$full) {
404       for ($i=0; $i<$count; $i++) {
405         $res[$i]["table"] = @mysql_field_table ($id, $i);
406         $res[$i]["name"]  = @mysql_field_name  ($id, $i);
407         $res[$i]["type"]  = @mysql_field_type  ($id, $i);
408         $res[$i]["len"]   = @mysql_field_len   ($id, $i);
409         $res[$i]["flags"] = @mysql_field_flags ($id, $i);
410       }
411     } else { // full
412       $res["num_fields"]= $count;
413     
414       for ($i=0; $i<$count; $i++) {
415         $res[$i]["table"] = @mysql_field_table ($id, $i);
416         $res[$i]["name"]  = @mysql_field_name  ($id, $i);
417         $res[$i]["type"]  = @mysql_field_type  ($id, $i);
418         $res[$i]["len"]   = @mysql_field_len   ($id, $i);
419         $res[$i]["flags"] = @mysql_field_flags ($id, $i);
420         $res["meta"][$res[$i]["name"]] = $i;
421       }
422     }
423     
424     // free the result only if we were called on a table
425     if ($table) @mysql_free_result($id);
426     return $res;
427   }*/
428
429 /********************************************************************************************************/
430   /* private: error handling */
431   function halt($msg) {
432     $this->Error = @mysql_error($this->Link_ID);
433     $this->Errno = @mysql_errno($this->Link_ID);
434     if ($this->Halt_On_Error == "no")
435       return;
436
437     $this->haltmsg($msg);
438
439     if ($this->Halt_On_Error != "report")
440       die("Session halted.");
441   }
442
443   function haltmsg($msg) {
444     printf("</td></tr></table><b>Database error:</b> %s<br />\n", $msg);
445     printf("<b>MySQL Error</b>: %s (%s)<br />\n",
446       $this->Errno,
447       $this->Error);
448   }
449
450   function table_names() {
451     $this->query("SHOW TABLES");
452     $i=0;
453     while ($info=mysql_fetch_row($this->Query_ID))
454      {
455       $return[$i]["table_name"]= $info[0];
456       $return[$i]["tablespace_name"]=$this->Database;
457       $return[$i]["database"]=$this->Database;
458       $i++;
459      }
460    return $return;
461   }
462 }
463 ?>
464
Note: See TracBrowser for help on using the browser.