Alternc  latest
Alternc logiel libre pour l'hébergement
db_mysql.php
Go to the documentation of this file.
1 <?php
2 
3 /*
4  ----------------------------------------------------------------------
5  LICENSE
6 
7  This program is free software; you can redistribute it and/or
8  modify it under the terms of the GNU General Public License (GPL)
9  as published by the Free Software Foundation; either version 2
10  of the License, or (at your option) any later version.
11 
12  This program is distributed in the hope that it will be useful,
13  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  GNU General Public License for more details.
16 
17  To read the license please visit http://www.gnu.org/copyleft/gpl.html
18  ----------------------------------------------------------------------
19 */
20 
21 /**
22  * Mysql Database class
23  *
24  * @copyright AlternC-Team 2000-2017 https://alternc.com/
25  *
26  */
27 class DB_Sql {
28 
29  /* public: connection parameters */
30  private $Host;
31  private $Database;
32  private $User;
33  private $Password;
34 
35  /* public: configuration parameters */
36  private $Auto_Free = False; // Set to True for automatic mysql_free_result()
37  private $Debug = False; // Set to 1 for debugging messages.
38  private $Halt_On_Error = "no"; // "yes" (halt with message), "no" (ignore errors quietly), "report" (ignore errror, but spit a warning)
39  private $Seq_Table = "db_sequence";
40 
41  /* public: result array and current row number */
42  public /* FIXME */ $Record = array();
43  private $Row = 0;
44  private $num_rows;
45 
46  /* public: current error number and error text */
47  private $Errno;
48  private $Error;
49 
50  /* private: link and query handles */
51  private $Query_String;
52 
53  /* PDO related variables */
54  private $pdo_instance = NULL;
55  private $pdo_query = NULL;
56 
57 
58  /**
59  * Constructor: Connect to the database server
60  */
61  function __construct($db, $host, $user, $passwd) {
62 
63  $dsn = sprintf('mysql:dbname=%s;host=%s', $db, $host);
64 
65  $options=array(
66 // \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
67  );
68  try {
69  $this->pdo_instance = new PDO($dsn, $user, $passwd, $options);
70  } catch (PDOException $e) {
71  echo "Mysql", "PDO instance", $e->getMessage();
72  return FALSE;
73  }
74  }
75 
76 
77  /**
78  * function for MySQL database connection management
79  *
80  * This function manages the connection to the MySQL database.
81  *
82  * @param $Database name of the database
83  * @param $Host DNS of the MySQL hosting server
84  * @param $User the user's name
85  * @param $Password the user's password
86  *
87  * @return the class variable $Link_ID
88  */
89  function connect($Database = "", $Host = "", $User = "", $Password = "") {
90  $this->halt('Mysql::connect() : This function should no longer be used');
91  /* Handle defaults */
92  if ("" == $Database)
94  if ("" == $Host)
96  if ("" == $User)
98  if ("" == $Password)
100 
101  if (!$this->pdo_instance) {
102  $dsn = sprintf('mysql:dbname=%s;host=%s', $Database, $Host);
103 
104  try {
105  $this->pdo_instance = new PDO($dsn, $User, $Password);
106  } catch (PDOException $e) {
107  $this->halt("Mysql::PDO_instance" . $e->getMessage());
108  return FALSE;
109  }
110  }
111 
112  return True;
113  }
114 
115  /**
116  * Discard the query result
117  *
118  * This function discards the last query result.
119  */
120  function free() {
121  $this->pdo_query->closeCursor();
122  }
123 
124 
125  function is_connected() {
126  return $this->pdo_instance != FALSE;
127  }
128 
129 
130  function last_error() {
131  return $this->Error;
132  }
133 
134 
135  /**
136  * Perform a query
137  *
138  * This function performs the MySQL query described in the string parameter
139  *
140  * @param a string describing the MySQL query
141  * @param arguments is an optionnal array for future use with PDO parametrized requests
142  * @return the $Query_ID class variable (null if fails)
143  */
144  function query($Query_String, $arguments = false) {
145  global $debug_alternc;
146 
147  if (empty($Query_String) || !$this->is_connected())
148  return FALSE;
149 
150  $this->Query_String = $Query_String;
151  if ($this->Debug)
152  printf("Debug: query = %s<br />\n", $Query_String);
153 
154  $debug_chrono_start = microtime(true);
155 
156  if ($arguments===false) {
157  $this->pdo_query = $this->pdo_instance->query($Query_String);
158  $exec_state = is_object($this->pdo_query);
159 
160  } else {
161 
162  $this->pdo_query = $this->pdo_instance->prepare($this->Query_String);
163  $exec_state = ($arguments) ? $this->pdo_query->execute($arguments)
164  : $this->pdo_query->execute();
165  // WARNING: this ternary is when we pass array() as $arguments
166  }
167 
168  $debug_chrono_start = (microtime(true) - $debug_chrono_start)*1000;
169  $this->Row = 0;
170 
171  if ($exec_state == FALSE) {
172  if (is_object($this->pdo_query)) {
173  $this->Errno = $this->pdo_query->errorCode();
174  $this->Error = $this->pdo_query->errorInfo();
175  } else {
176  $this->Errno = $this->pdo_instance->errorCode();
177  $this->Error = $this->pdo_instance->errorInfo();
178  }
179 
180  if( defined("THROW_EXCEPTIONS") && THROW_EXCEPTIONS ){
181  throw new \Exception("Mysql query failed : $this->Error");
182  }
183  $this->halt("SQL Error: ".$Query_String);
184  return FALSE;
185  }
186 
187  if (isset($debug_alternc)) {
188  $debug_alternc->add("SQL Query : (".substr($debug_chrono_start,0,5)." ms)\t $Query_String");
189  $debug_alternc->nb_sql_query++;
190  $debug_alternc->tps_sql_query += $debug_chrono_start;
191  }
192 
193  return TRUE;
194  }
195 
196 
197  /**
198  * walk result set
199  *
200  * This function tests if a new record is available in the current
201  * query result.
202  *
203  * @return TRUE if a new record is available
204  */
205  function next_record() {
206  if (!$this->pdo_query) {
207  $this->halt("next_record called with no query pending.");
208  return FALSE;
209  }
210 
211  $this->Record = $this->pdo_query->fetch(PDO::FETCH_BOTH);
212  $this->Row++;
213  $this->Errno = $this->pdo_query->errorCode();
214  $this->Error = $this->pdo_query->errorInfo();
215 
216  if ($this->Record == FALSE) {
217  if ($this->Auto_Free)
218  $this->free();
219  return FALSE;
220  }
221 
222  return TRUE;
223  }
224 
225  /* pdo equivalent of fetchAll() */
226  function fetchAll() {
227  if (!$this->pdo_query) {
228  $this->halt("next_record called with no query pending.");
229  return FALSE;
230  }
231 
232  $data = $this->pdo_query->fetchAll(PDO::FETCH_BOTH);
233  $this->Errno = $this->pdo_query->errorCode();
234  $this->Error = $this->pdo_query->errorInfo();
235 
236  if ($data == FALSE) {
237  if ($this->Auto_Free)
238  $this->free();
239  return FALSE;
240  }
241 
242  return $data;
243  }
244 
245  /* pdo equivalent of fetch() */
246  function fetch($mode=PDO::FETCH_ASSOC) {
247  if (!$this->pdo_query) {
248  $this->halt("next_record called with no query pending.");
249  return FALSE;
250  }
251 
252  $data = $this->pdo_query->fetch($mode);
253  $this->Errno = $this->pdo_query->errorCode();
254  $this->Error = $this->pdo_query->errorInfo();
255 
256  if ($data == FALSE) {
257  if ($this->Auto_Free)
258  $this->free();
259  return FALSE;
260  }
261 
262  return $data;
263  }
264 
265  /**
266  * table locking
267  */
268  function lock($table, $mode="write") {
269  if (!$this->is_connected())
270  return FALSE;
271 
272  $query="lock tables ";
273  if (is_array($table)) {
274  while (list($key,$value)=each($table)) {
275  if ($key=="read" && $key!=0) {
276  $query.="$value read, ";
277  } else {
278  $query.="$value $mode, ";
279  }
280  }
281  $query=substr($query,0,-2);
282  } else {
283  $query.="$table $mode";
284  }
285 
286 
287  if (!$this->query($query)) {
288  $this->halt("lock($table, $mode) failed.");
289  return FALSE;
290  }
291 
292  return TRUE;
293 
294  }
295 
296  /**
297  * table unlocking
298  */
299  function unlock() {
300  if (!$this->is_connected())
301  return FALSE;
302 
303  if (!$this->query('unlock tables')) {
304  $this->halt("unlock() failed.");
305  return FALSE;
306  }
307  }
308 
309 
310  /**
311  * evaluate the result (size, width)
312  */
313  function affected_rows() {
314  if (!$this->pdo_query) return 0;
315  return $this->pdo_query->rowCount();
316  }
317  function num_rows() {
318  if (!$this->pdo_query) return 0;
319  return $this->pdo_query->rowCount();
320  }
321 
322  function num_fields() {
323  if (!$this->pdo_query) return 0;
324  return $this->pdo_query->columnCount();
325  }
326 
327  /**
328  * shorthand notation
329  */
330  function nf() {
331  return $this->num_rows();
332  }
333 
334  function np() {
335  print $this->num_rows();
336  }
337 
338 
339  /**
340  * @param string $Name
341  * @return integer
342  */
343  function f($Name) {
344  if (isset($this->Record[$Name]))
345  return $this->Record[$Name];
346  else
347  return false;
348  }
349 
350 
351  function current_record() {
352  return $this->Record;
353  }
354 
355 
356  function p($Name) {
357  print $this->Record[$Name];
358  }
359 
360 
361  function lastid() {
362  return $this->pdo_instance->lastInsertId();
363  }
364 
365 
366  /**
367  * Escape a string to use it into a SQL PDO query
368  * @param string string to escape
369  * @return string escaped string
370  */
371  function quote($string) {
372  return $this->pdo_instance->quote($string);
373  }
374 
375 
376  /**
377  * Execute a direct query, not getting any result back
378  * @param query string query to execute
379  * @return integer the number of affected rows
380  */
381  function exec($query) {
382  return $this->pdo_instance->exec($query);
383  }
384 
385 
386  /**
387  * get next sequence numbers
388  */
389  function nextid($seq_name) {
390  if (!$this->is_connected())
391  return FALSE;
392 
393  if ($this->lock($this->Seq_Table)) {
394  /* get sequence number (locked) and increment */
395  $q = sprintf("select nextid from %s where seq_name = '%s'",
396  $this->Seq_Table,
397  $seq_name);
398  $this->query($q);
399  $this->next_record();
400 
401  $id = $this->f('nextid');
402 
403  /* No current value, make one */
404  if (!$id) {
405  $currentid = 0;
406  $q = sprintf("insert into %s values('%s', %s)",
407  $this->Seq_Table,
408  $seq_name,
409  $currentid);
410  $this->query($q);
411  } else {
412  $currentid = $id;
413  }
414 
415  $nextid = $currentid + 1;
416  $q = sprintf("update %s set nextid = '%s' where seq_name = '%s'",
417  $this->Seq_Table,
418  $nextid,
419  $seq_name);
420  $this->query($q);
421  $this->unlock();
422  } else {
423  $this->halt("cannot lock ".$this->Seq_Table." - has it been created?");
424  return FALSE;
425  }
426 
427  return $nextid;
428  }
429 
430 
431  /**
432  * DEPRECATED return table metadata
433  */
434  function metadata($table='',$full=false) {
435  global $msg;
436  $msg->raise("ERROR", 'Mysql', 'function is no longer implemented (metadata())');
437  return FALSE;
438  }
439 
440  /**
441  * private: error handling
442  */
443  function halt($msg) {
444  if ($this->Halt_On_Error == "no")
445  return;
446 
447  $this->haltmsg($msg);
448 
449  if ($this->Halt_On_Error != "report")
450  die("Session halted.");
451  }
452 
453 
454  /**
455  * private: error handling
456  */
457  function haltmsg($msg) {
458  printf("</td></tr></table><b>Database error:</b> %s<br />\n", $msg);
459  printf("<b>MySQL Error</b>: %s (%s)<br />\n",
460  $this->Errno,
461  implode("\n", $this->Error));
462  }
463 
464 
465  function table_names() {
466  $this->query("SHOW TABLES");
467  $return = array();
468  while ($this->next_record())
469  $return[] = array('table_name' => $this->p(0), 'tablespace_name' => $this->Database, 'database' => $this->Database);
470 
471  return $return;
472  }
473 
474 } /* Class DB_Sql */
475 
$query
Definition: 3.0.0~3.php:37
$mode
Definition: adm_tldedit.php:40
global $db
Definition: bootstrap.php:26
$msg
Definition: bootstrap.php:75
Mysql Database class.
Definition: db_mysql.php:27
num_rows()
Definition: db_mysql.php:317
quote($string)
Escape a string to use it into a SQL PDO query.
Definition: db_mysql.php:371
$Database
Definition: db_mysql.php:31
free()
Discard the query result.
Definition: db_mysql.php:120
nf()
shorthand notation
Definition: db_mysql.php:330
num_fields()
Definition: db_mysql.php:322
f($Name)
Definition: db_mysql.php:343
table_names()
Definition: db_mysql.php:465
$Halt_On_Error
Definition: db_mysql.php:38
affected_rows()
evaluate the result (size, width)
Definition: db_mysql.php:313
$num_rows
Definition: db_mysql.php:44
halt($msg)
private: error handling
Definition: db_mysql.php:443
haltmsg($msg)
private: error handling
Definition: db_mysql.php:457
exec($query)
Execute a direct query, not getting any result back.
Definition: db_mysql.php:381
fetch($mode=PDO::FETCH_ASSOC)
Definition: db_mysql.php:246
$Auto_Free
Definition: db_mysql.php:36
$Query_String
Definition: db_mysql.php:51
p($Name)
Definition: db_mysql.php:356
lock($table, $mode="write")
table locking
Definition: db_mysql.php:268
query($Query_String, $arguments=false)
Perform a query.
Definition: db_mysql.php:144
current_record()
Definition: db_mysql.php:351
__construct($db, $host, $user, $passwd)
Constructor: Connect to the database server.
Definition: db_mysql.php:61
fetchAll()
Definition: db_mysql.php:226
$pdo_query
Definition: db_mysql.php:55
lastid()
Definition: db_mysql.php:361
next_record()
walk result set
Definition: db_mysql.php:205
$pdo_instance
Definition: db_mysql.php:54
nextid($seq_name)
get next sequence numbers
Definition: db_mysql.php:389
connect($Database="", $Host="", $User="", $Password="")
function for MySQL database connection management
Definition: db_mysql.php:89
unlock()
table unlocking
Definition: db_mysql.php:299
is_connected()
Definition: db_mysql.php:125
metadata($table='', $full=false)
DEPRECATED return table metadata.
Definition: db_mysql.php:434
$Seq_Table
Definition: db_mysql.php:39
$Password
Definition: db_mysql.php:33
last_error()
Definition: db_mysql.php:130
$host
Definition: config.php:71
$value
$string
Definition: logs_tail.php:38
print
Definition: mail_add.php:92
$q
Definition: menu_aws.php:32
$user
Definition: bootstrap.php:84
const THROW_EXCEPTIONS
Definition: bootstrap.php:69
if(!isset($is_include)) if(! $key &&! $crt) $id
if(empty($_POST['key'])||empty($_POST['val'])) $key
Definition: tempovars.php:14