OSDN Git Service

8c02003d85e9270ba05d47fe4aa768b6cd6647bf
[nucleus-jp/nucleus-jp-ancient.git] / nucleus / libs / sql / pdo.php
1 <?php
2
3 /*
4  * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
5  * Copyright (C) 2002-2012 The Nucleus Group
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
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * (see nucleus/documentation/index.html#license for more info)
12  *
13  * complete sql_* wrappers for mysql functions
14  *
15  * functions moved from globalfunctions.php: sql_connect, sql_disconnect, sql_query
16  */
17
18 $MYSQL_CONN = 0;
19 global $SQL_DBH;
20 $SQL_DBH = NULL;
21
22 if (!function_exists('sql_fetch_assoc'))
23 {
24 /**
25  * Errors before the database connection has been made
26  */
27         function startUpError($msg, $title) {
28                 if (!defined('_CHARSET')) {
29                         define('_CHARSET', 'UTF-8');
30                 }
31                 if (!defined('_HTML_XML_NAME_SPACE_AND_LANG_CODE')) {
32                         define('_HTML_XML_NAME_SPACE_AND_LANG_CODE', 'xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us"');
33                 }
34                 sendContentType('text/html','',_CHARSET);
35                 ?>
36 <html <?php echo _HTML_XML_NAME_SPACE_AND_LANG_CODE; ?>>
37         <head><meta http-equiv="Content-Type" content="text/html; charset=<?php echo _CHARSET?>" />
38         <title><?php echo htmlspecialchars($title,ENT_QUOTES)?></title></head>
39         <body>
40                 <h1><?php echo htmlspecialchars($title,ENT_QUOTES)?></h1>
41                 <?php echo $msg?> 
42         </body>
43 </html>
44 <?php
45                 exit;
46         }
47         
48 /**
49  * Connects to mysql server
50  */
51         function sql_connect_args($mysql_host = 'localhost', $mysql_user = '', $mysql_password = '', $mysql_database = '') {
52                 global $MYSQL_HANDLER;
53                 
54                 try {
55                         if (strpos($mysql_host,':') === false) {
56                                 $host = $mysql_host;
57                                 $port = '';
58                                 $portnum = '';
59                         }
60                         else {
61                                 list($host,$port) = explode(":",$mysql_host);
62                                 if (isset($port)) {
63                                         $portnum = $port;
64                                         $port = ';port='.trim($port);
65                                 }
66                                 else {
67                                         $port = '';
68                                         $portnum = '';
69                                 }
70                         }
71                         
72                         switch ($MYSQL_HANDLER[1]) {
73                                 case 'sybase':
74                                 case 'dblib':
75                                         if (is_numeric($portnum)) $port = ':'.intval($portnum);
76                                         else $port = '';
77                                         $DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$mysql_database, $mysql_user, $mysql_password);
78                                 break;
79                                 case 'mssql':
80                                         if (is_numeric($portnum)) $port = ','.intval($portnum);
81                                         else $port = '';
82                                         $DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$mysql_database, $mysql_user, $mysql_password);
83                                 break;
84                                 case 'oci':
85                                         if (is_numeric($portnum)) $port = ':'.intval($portnum);
86                                         else $port = '';
87                                         $DBH = new PDO($MYSQL_HANDLER[1].':dbname=//'.$host.$port.'/'.$mysql_database, $mysql_user, $mysql_password);
88                                 break;
89                                 case 'odbc':
90                                         if (is_numeric($portnum)) $port = ';PORT='.intval($portnum);
91                                         else $port = '';
92                                         $DBH = new PDO($MYSQL_HANDLER[1].':DRIVER={IBM DB2 ODBC DRIVER};HOSTNAME='.$host.$port.';DATABASE='.$mysql_database.';PROTOCOL=TCPIP;UID='.$mysql_user.';PWD='.$mysql_password);
93
94                                 break;
95                                 case 'pgsql':
96                                         if (is_numeric($portnum)) $port = ';port='.intval($portnum);
97                                         else $port = '';
98                                         $DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$mysql_database, $mysql_user, $mysql_password);
99                                 break;
100                                 case 'sqlite':
101                                 case 'sqlite2':
102                                         if (is_numeric($portnum)) $port = ':'.intval($portnum);
103                                         else $port = '';
104                                         $DBH = new PDO($MYSQL_HANDLER[1].':'.$mysql_database, $mysql_user, $mysql_password);
105                                 break;
106                                 default:
107                                         //mysql
108                                         $DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$mysql_database, $mysql_user, $mysql_password);
109                                 break;
110                         }
111         
112                         
113                                                 
114                 } catch (PDOException $e) {
115                         $DBH =NULL;
116                         startUpError('<p>a1 Error!: ' . $e->getMessage() . '</p>', 'Connect Error');
117                 }
118 //echo '<hr />DBH: '.print_r($DBH,true).'<hr />';               
119                 return $DBH;
120         }
121         
122 /**
123  * Connects to mysql server
124  */
125         function sql_connect() {
126                 global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_CONN, $MYSQL_HANDLER, $SQL_DBH;
127                 $SQL_DBH = NULL;
128                 try {
129                         if (strpos($MYSQL_HOST,':') === false) {
130                                 $host = $MYSQL_HOST;
131                                 $port = '';
132                         }
133                         else {
134                                 list($host,$port) = explode(":",$MYSQL_HOST);
135                                 if (isset($port)) {
136                                         $portnum = $port;
137                                         $port = ';port='.trim($port);
138                                 }
139                                 else {
140                                         $port = '';
141                                         $portnum = '';
142                                 }
143                         }
144                         
145                         switch ($MYSQL_HANDLER[1]) {
146                                 case 'sybase':
147                                 case 'dblib':
148                                         if (is_numeric($portnum)) $port = ':'.intval($portnum);
149                                         else $port = '';
150                                         $SQL_DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$MYSQL_DATABASE, $MYSQL_USER, $MYSQL_PASSWORD);
151                                 break;
152                                 case 'mssql':
153                                         if (is_numeric($portnum)) $port = ','.intval($portnum);
154                                         else $port = '';
155                                         $SQL_DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$MYSQL_DATABASE, $MYSQL_USER, $MYSQL_PASSWORD);
156                                 break;
157                                 case 'oci':
158                                         if (is_numeric($portnum)) $port = ':'.intval($portnum);
159                                         else $port = '';
160                                         $SQL_DBH = new PDO($MYSQL_HANDLER[1].':dbname=//'.$host.$port.'/'.$MYSQL_DATABASE, $MYSQL_USER, $MYSQL_PASSWORD);
161                                 break;
162                                 case 'odbc':
163                                         if (is_numeric($portnum)) $port = ';PORT='.intval($portnum);
164                                         else $port = '';
165                                         $SQL_DBH = new PDO($MYSQL_HANDLER[1].':DRIVER={IBM DB2 ODBC DRIVER};HOSTNAME='.$host.$port.';DATABASE='.$MYSQL_DATABASE.';PROTOCOL=TCPIP;UID='.$MYSQL_USER.';PWD='.$MYSQL_PASSWORD);
166
167                                 break;
168                                 case 'pgsql':
169                                         if (is_numeric($portnum)) $port = ';port='.intval($portnum);
170                                         else $port = '';
171                                         $SQL_DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$MYSQL_DATABASE, $MYSQL_USER, $MYSQL_PASSWORD);
172                                 break;
173                                 case 'sqlite':
174                                 case 'sqlite2':
175                                         if (is_numeric($portnum)) $port = ':'.intval($portnum);
176                                         else $port = '';
177                                         $SQL_DBH = new PDO($MYSQL_HANDLER[1].':'.$MYSQL_DATABASE, $MYSQL_USER, $MYSQL_PASSWORD);
178                                 break;
179                                 default:
180                                         //mysql
181                                         $SQL_DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$MYSQL_DATABASE, $MYSQL_USER, $MYSQL_PASSWORD);
182                                 break;
183                         }
184
185                         //$SQL_DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$MYSQL_DATABASE, $MYSQL_USER, $MYSQL_PASSWORD);
186                         
187 // <add for garble measure>
188                         if (strpos($MYSQL_HANDLER[1], 'mysql') === 0) {
189                                 if (defined('_CHARSET')){
190                                         $charset  = _CHARSET;
191                                 }else{
192                                         $resource = $SQL_DBH->query("show variables LIKE 'character_set_database'");
193                                         $resource->bindColumn('Value', $charset);
194                                         $resource->fetchAll();
195                                         // in trouble of encoding,uncomment the following line.
196                                         // $charset = "ujis";
197                                         // $charset = "utf8";
198                                 }
199                                 sql_set_charset_jp($charset);
200                         }
201 // </add for garble measure>*/
202                 } catch (PDOException $e) {
203                         $SQL_DBH = NULL;
204                         startUpError('<p>a2 Error!: ' . $e->getMessage() . '</p>', 'Connect Error');
205                 }
206 //              echo '<hr />DBH: '.print_r($SQL_DBH,true).'<hr />';             
207                 $MYSQL_CONN &= $SQL_DBH;
208                 return $SQL_DBH;
209
210         }
211
212 /**
213  * disconnects from SQL server
214  */
215         function sql_disconnect(&$dbh=NULL) {
216                 global $SQL_DBH;
217                 if (is_null($dbh)) $SQL_DBH = NULL;
218                 else $dbh = NULL;
219         }
220         
221         function sql_close(&$dbh=NULL) {
222                 global $SQL_DBH;
223                 if (is_null($dbh)) $SQL_DBH = NULL;
224                 else $dbh = NULL;
225         }
226         
227 /**
228  * executes an SQL query
229  */
230         function sql_query($query,$dbh=NULL) {
231                 global $SQLCount,$SQL_DBH;
232                 $SQLCount++;
233 //echo '<hr />SQL_DBH: ';
234 //print_r($SQL_DBH);
235 //echo '<hr />DBH: ';
236 //print_r($dbh);
237 //echo '<hr />';
238 //echo $query.'<hr />';
239                 if (is_null($dbh)) $res = $SQL_DBH->query($query);
240                 else $res = $dbh->query($query);
241                 if ($res->errorCode() != '00000') {
242                         $errors = $res->errorInfo();
243                         print("SQL error with query $query: " . $errors[0].'-'.$errors[1].' '.$errors[2] . '<p />');
244                 }
245                 
246                 return $res;
247         }
248         
249 /**
250  * executes an SQL error
251  */
252         function sql_error($dbh=NULL)
253         {
254                 global $SQL_DBH;
255                 if (is_null($dbh)) $error = $SQL_DBH->errorInfo();
256                 else $error = $dbh->errorInfo();
257                 if ($error[0] != '00000') {
258                         return $error[0].'-'.$error[1].' '.$error[2];
259                 }
260                 else return '';
261         }
262         
263 /**
264  * executes an SQL db select
265  */
266         function sql_select_db($db,&$dbh=NULL)
267         {
268                 global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_CONN, $MYSQL_HANDLER, $SQL_DBH;
269 //echo '<hr />'.print_r($dbh,true).'<hr />';
270 //exit;
271                 if (is_null($dbh)) { 
272                         try {
273                                 $SQL_DBH = NULL;
274                                 list($host,$port) = explode(":",$MYSQL_HOST);
275                                 if (isset($port)) {
276                                         $portnum = $port;
277                                         $port = ';port='.trim($port);
278                                 }
279                                 else {
280                                         $port = '';
281                                         $portnum = '';
282                                 }
283                                 //$SQL_DBH = new PDO($MYSQL_HANDLER[1].':host='.trim($host).$port.';dbname='.$db, $MYSQL_USER, $MYSQL_PASSWORD);
284                                 //$SQL_DBH = sql_connect();
285                                 switch ($MYSQL_HANDLER[1]) {
286                                         case 'sybase':
287                                         case 'dblib':
288                                                 if (is_numeric($portnum)) $port = ':'.intval($portnum);
289                                                 else $port = '';
290                                                 $SQL_DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$db, $MYSQL_USER, $MYSQL_PASSWORD);
291                                         break;
292                                         case 'mssql':
293                                                 if (is_numeric($portnum)) $port = ','.intval($portnum);
294                                                 else $port = '';
295                                                 $SQL_DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$db, $MYSQL_USER, $MYSQL_PASSWORD);
296                                         break;
297                                         case 'oci':
298                                                 if (is_numeric($portnum)) $port = ':'.intval($portnum);
299                                                 else $port = '';
300                                                 $SQL_DBH = new PDO($MYSQL_HANDLER[1].':dbname=//'.$host.$port.'/'.$db, $MYSQL_USER, $MYSQL_PASSWORD);
301                                         break;
302                                         case 'odbc':
303                                                 if (is_numeric($portnum)) $port = ';PORT='.intval($portnum);
304                                                 else $port = '';
305                                                 $SQL_DBH = new PDO($MYSQL_HANDLER[1].':DRIVER={IBM DB2 ODBC DRIVER};HOSTNAME='.$host.$port.';DATABASE='.$db.';PROTOCOL=TCPIP;UID='.$MYSQL_USER.';PWD='.$MYSQL_PASSWORD);
306
307                                         break;
308                                         case 'pgsql':
309                                                 if (is_numeric($portnum)) $port = ';port='.intval($portnum);
310                                                 else $port = '';
311                                                 $SQL_DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$db, $MYSQL_USER, $MYSQL_PASSWORD);
312                                         break;
313                                         case 'sqlite':
314                                         case 'sqlite2':
315                                                 if (is_numeric($portnum)) $port = ':'.intval($portnum);
316                                                 else $port = '';
317                                                 $SQL_DBH = new PDO($MYSQL_HANDLER[1].':'.$db, $MYSQL_USER, $MYSQL_PASSWORD);
318                                         break;
319                                         default:
320                                                 //mysql
321                                                 $SQL_DBH = new PDO($MYSQL_HANDLER[1].':host='.$host.$port.';dbname='.$db, $MYSQL_USER, $MYSQL_PASSWORD);
322                                         break;
323                                 }
324                                 return 1;
325                         } catch (PDOException $e) {
326                                 startUpError('<p>a3 Error!: ' . $e->getMessage() . '</p>', 'Connect Error');
327                                 return 0;
328                         }
329                 }
330                 else {
331                         if ($dbh->exec("USE $db") !== false) return 1;
332                         else return 0;
333                 }
334         }
335         
336 /**
337  * executes an SQL real escape 
338  */
339         function sql_real_escape_string($val,$dbh=NULL)
340         {
341                 return addslashes($val);
342         }
343         
344 /**
345  * executes an PDO::quote() like escape, ie adds quotes arround the string and escapes chars as needed 
346  */
347         function sql_quote_string($val,$dbh=NULL) {
348                 global $SQL_DBH;
349                 if (is_null($dbh))
350                         return $SQL_DBH->quote($val);
351                 else
352                         return $dbh->quote($val);
353         }
354         
355 /**
356  * executes an SQL insert id
357  */
358         function sql_insert_id($dbh=NULL)
359         {   
360                 global $SQL_DBH;
361                 if (is_null($dbh))
362                         return $SQL_DBH->lastInsertId();
363                 else
364                         return $dbh->lastInsertId();
365         }
366         
367 /**
368  * executes an SQL result request
369  */
370         function sql_result($res, $row = 0, $col = 0)
371         {
372                 $results = array();
373                 if (intval($row) < 1) {
374                         $results = $res->fetch(PDO::FETCH_BOTH);
375                         return $results[$col];
376                 }
377                 else {
378                         for ($i = 0; $i < intval($row); $i++) {
379                                 $results = $res->fetch(PDO::FETCH_BOTH);
380                         }
381                         $results = $res->fetch(PDO::FETCH_BOTH);
382                         return $results[$col];
383                 }
384         }
385         
386 /**
387  * frees sql result resources
388  */
389         function sql_free_result($res)
390         {
391                 $res = NULL;
392                 return true;
393         }
394         
395 /**
396  * returns number of rows in SQL result
397  */
398         function sql_num_rows($res)
399         {
400                 return $res->rowCount();
401         }
402         
403 /**
404  * returns number of rows affected by SQL query
405  */
406         function sql_affected_rows($res)
407         {
408                 return $res->rowCount();
409         }
410         
411 /**
412  * Get number of fields in result
413  */
414         function sql_num_fields($res)
415         {
416                 return $res->columnCount();
417         }
418         
419 /**
420  * fetches next row of SQL result as an associative array
421  */
422         function sql_fetch_assoc($res)
423         {
424                 $results = array();
425                 $results = $res->fetch(PDO::FETCH_ASSOC);   
426                 return $results;
427         }
428         
429 /**
430  * Fetch a result row as an associative array, a numeric array, or both
431  */
432         function sql_fetch_array($res)
433         {
434                 $results = array();
435                 $results = $res->fetch(PDO::FETCH_BOTH);
436                 return $results;
437         }
438         
439 /**
440  * fetches next row of SQL result as an object
441  */
442         function sql_fetch_object($res)
443         {
444                 $results = NULL;
445                 $results = $res->fetchObject(); 
446                 return $results;
447         }
448         
449 /**
450  * Get a result row as an enumerated array
451  */
452         function sql_fetch_row($res)
453         {
454                 $results = array();
455                 $results = $res->fetch(PDO::FETCH_NUM); 
456                 return $results;
457         }
458         
459 /**
460  * Get column information from a result and return as an object
461  */
462         function sql_fetch_field($res,$offset = 0)
463         {
464                 $results = array();
465                 $obj = NULL;
466                 $results = $res->getColumnMeta($offset);
467                 foreach($results as $key=>$value) {
468                         $obj->$key = $value;
469                 }
470                 return $obj;
471         }
472         
473 /**
474  * Get current system status (returns string)
475  */
476         function sql_stat($dbh=NULL)
477         {
478                 //not implemented
479                 global $SQL_DBH;
480                 if (is_null($dbh))
481                         return '';
482                 else
483                 return '';
484         }
485         
486 /**
487  * Returns the name of the character set
488  */
489         function sql_client_encoding($dbh=NULL)
490         {
491                 //not implemented
492                 global $SQL_DBH;
493                 if (is_null($dbh))
494                         return '';
495                 else
496                         return '';
497         }
498         
499 /**
500  * Get SQL client version
501  */
502         function sql_get_client_info()
503         {
504                 global $SQL_DBH;
505                 return $SQL_DBH->getAttribute(constant("PDO::ATTR_CLIENT_VERSION"));
506         }
507         
508 /**
509  * Get SQL server version
510  */
511         function sql_get_server_info($dbh=NULL)
512         {
513                 global $SQL_DBH;
514                 if (is_null($dbh))
515                         return $SQL_DBH->getAttribute(constant("PDO::ATTR_SERVER_VERSION"));
516                 else
517                         return $dbh->getAttribute(constant("PDO::ATTR_SERVER_VERSION"));
518         }
519         
520 /**
521  * Returns a string describing the type of SQL connection in use for the connection or FALSE on failure
522  */
523         function sql_get_host_info($dbh=NULL)
524         {
525                 global $SQL_DBH;
526                 if (is_null($dbh))
527                         return $SQL_DBH->getAttribute(constant("PDO::ATTR_SERVER_INFO"));
528                 else
529                         return $dbh->getAttribute(constant("PDO::ATTR_SERVER_INFO"));
530         }
531         
532 /**
533  * Returns the SQL protocol on success, or FALSE on failure. 
534  */
535         function sql_get_proto_info($dbh=NULL)
536         {
537                 //not implemented
538                 global $SQL_DBH;
539                 if (is_null($dbh))
540                         return false;
541                 else
542                         return false;
543         }
544
545 /**
546  * Get the name of the specified field in a result
547  */
548         function sql_field_name($res, $offset = 0)
549         {
550                 $column = $res->getColumnMeta($offset);
551                 if ($column) {
552                         return $column['name'];
553                 }
554                 return false;
555         }
556
557 /**************************************************************************
558         Unimplemented mysql_* functions
559         
560 # mysql_ data_ seek (maybe useful)
561 # mysql_ errno (maybe useful)
562 # mysql_ fetch_ lengths (maybe useful)
563 # mysql_ field_ flags (maybe useful)
564 # mysql_ field_ len (maybe useful)
565 # mysql_ field_ name (maybe useful)
566 # mysql_ field_ seek (maybe useful)
567 # mysql_ field_ table (maybe useful)
568 # mysql_ field_ type (maybe useful)
569 # mysql_ info (maybe useful)
570 # mysql_ list_ processes (maybe useful)
571 # mysql_ ping (maybe useful)
572 # mysql_ set_ charset (maybe useful, requires php >=5.2.3 and mysql >=5.0.7)
573 # mysql_ thread_ id (maybe useful)
574
575 # mysql_ db_ name (useful only if working on multiple dbs which we do not do)
576 # mysql_ list_ dbs (useful only if working on multiple dbs which we do not do)
577
578 # mysql_ pconnect (probably not useful and could cause some unintended performance issues)
579 # mysql_ unbuffered_ query (possibly useful, but complicated and not supported by all database drivers (pdo))
580
581 # mysql_ change_ user (deprecated)
582 # mysql_ create_ db (deprecated)
583 # mysql_ db_ query (deprecated)
584 # mysql_ drop_ db (deprecated)
585 # mysql_ escape_ string (deprecated)
586 # mysql_ list_ fields (deprecated)
587 # mysql_ list_ tables (deprecated)
588 # mysql_ tablename (deprecated)
589
590 *******************************************************************/
591
592         /*
593          * for preventing I/O strings from auto-detecting the charactor encodings by MySQL
594          * since 3.62_beta-jp
595          * Jan.20, 2011 by kotorisan and cacher
596          * refering to their conversation below,
597          * http://japan.nucleuscms.org/bb/viewtopic.php?p=26581
598          * 
599          * NOTE:        shift_jis is only supported for output. Using shift_jis in DB is prohibited.
600          * NOTE:        iso-8859-x,windows-125x if _CHARSET is unset.
601          */
602         function sql_set_charset_jp($charset) {
603                 global $MYSQL_HANDLER,$SQL_DBH;
604                 if (strpos($MYSQL_HANDLER[1], 'mysql') === 0) {
605                         switch(strtolower($charset)){\r
606                                 case 'utf-8':
607                                 case 'utf8':\r
608                                         $charset = 'utf8';\r
609                                         break;\r
610                                 case 'euc-jp':
611                                 case 'ujis':\r
612                                         $charset = 'ujis';\r
613                                         break;\r
614                                 case 'gb2312':\r
615                                         $charset = 'gb2312';\r
616                                         break;
617                                 /*\r
618                                 case 'shift_jis':
619                                 case 'sjis':\r
620                                         $charset = 'sjis';\r
621                                         break;
622                                 */\r
623                                 default:
624                                         $charset = 'latin1';\r
625                                         break;\r
626                         }
627                         $mySqlVer = implode('.', array_map('intval', explode('.', sql_get_server_info())));
628                         if (version_compare($mySqlVer, '4.1.0', '>=')) {
629                                 $res = $SQL_DBH->exec("SET CHARACTER SET " . $charset);
630                         }
631                 }
632                 return $res;
633         }
634 }
635 ?>