File: adodb-mysqli.inc.php

package info (click to toggle)
libphp-adodb 5.21.4-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 2,276 kB
  • sloc: php: 35,839; xml: 52; sql: 32; makefile: 5
file content (1749 lines) | stat: -rw-r--r-- 47,440 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
<?php
/**
 * MySQL improved driver (mysqli)
 *
 * This is the preferred driver for MySQL connections. It  supports both
 * transactional and non-transactional table types. You can use this as a
 * drop-in replacement for both the mysql and mysqlt drivers.
 * As of ADOdb Version 5.20.0, all other native MySQL drivers are deprecated.
 *
 * This file is part of ADOdb, a Database Abstraction Layer library for PHP.
 *
 * @package ADOdb
 * @link https://adodb.org Project's web site and documentation
 * @link https://github.com/ADOdb/ADOdb Source code and issue tracker
 *
 * The ADOdb Library is dual-licensed, released under both the BSD 3-Clause
 * and the GNU Lesser General Public Licence (LGPL) v2.1 or, at your option,
 * any later version. This means you can use it in proprietary products.
 * See the LICENSE.md file distributed with this source code for details.
 * @license BSD-3-Clause
 * @license LGPL-2.1-or-later
 *
 * @copyright 2000-2013 John Lim
 * @copyright 2014 Damien Regad, Mark Newnham and the ADOdb community
 */

// security - hide paths
if (!defined('ADODB_DIR')) {
	die();
}

if (!defined("_ADODB_MYSQLI_LAYER")) {
	define("_ADODB_MYSQLI_LAYER", 1);

// PHP5 compat...
if (! defined("MYSQLI_BINARY_FLAG"))  define("MYSQLI_BINARY_FLAG", 128);
if (!defined('MYSQLI_READ_DEFAULT_GROUP')) define('MYSQLI_READ_DEFAULT_GROUP',1);

/**
 * Class ADODB_mysqli
 */
class ADODB_mysqli extends ADOConnection {
	var $databaseType = 'mysqli';
	var $dataProvider = 'mysql';
	var $hasInsertID = true;
	var $hasAffectedRows = true;
	var $metaTablesSQL = "SELECT
			TABLE_NAME,
			CASE WHEN TABLE_TYPE = 'VIEW' THEN 'V' ELSE 'T' END
		FROM INFORMATION_SCHEMA.TABLES
		WHERE TABLE_SCHEMA=";
	var $metaColumnsSQL = "SHOW COLUMNS FROM `%s`";
	var $fmtTimeStamp = "'Y-m-d H:i:s'";
	var $hasLimit = true;
	var $hasMoveFirst = true;
	var $hasGenID = true;
	var $isoDates = true; // accepts dates in ISO format
	var $sysDate = 'CURDATE()';
	var $sysTimeStamp = 'NOW()';
	var $hasTransactions = true;
	var $forceNewConnect = false;
	var $poorAffectedRows = true;
	var $clientFlags = 0;
	var $substr = "substring";
	var $port = 3306; //Default to 3306 to fix HHVM bug
	var $socket = ''; //Default to empty string to fix HHVM bug
	var $_bindInputArray = false;
	var $nameQuote = '`';		/// string to use to quote identifiers and names
	var $optionFlags = array(array(MYSQLI_READ_DEFAULT_GROUP,0));
	var $arrayClass = 'ADORecordSet_array_mysqli';
	var $multiQuery = false;
	var $ssl_key = null;
	var $ssl_cert = null;
	var $ssl_ca = null;
	var $ssl_capath = null;
	var $ssl_cipher = null;

	/**
	 * Tells the insert_id method how to obtain the last value, depending on whether
	 * we are using a stored procedure or not
	 */
	private $usePreparedStatement = false;
	private $useLastInsertStatement = false;

	/**
	 * @var bool True if the last executed statement is a SELECT {@see _query()}
	 */
	private $isSelectStatement = false;

	/**
	 * ADODB_mysqli constructor.
	 */
	public function __construct()
	{
		parent::__construct();

		// Forcing error reporting mode to OFF, which is no longer the default
		// starting with PHP 8.1 (see #755)
		mysqli_report(MYSQLI_REPORT_OFF);
	}


	/**
	 * Sets the isolation level of a transaction.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:settransactionmode
	 *
	 * @param string $transaction_mode The transaction mode to set.
	 *
	 * @return void
	 */
	function SetTransactionMode($transaction_mode)
	{
		$this->_transmode = $transaction_mode;
		if (empty($transaction_mode)) {
			$this->execute('SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ');
			return;
		}
		if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
		$this->execute("SET SESSION TRANSACTION ".$transaction_mode);
	}

	/**
	 * Adds a parameter to the connection string.
	 *
	 * Parameter must be one of the the constants listed in mysqli_options().
	 * @see https://www.php.net/manual/en/mysqli.options.php
	 *
	 * @param int $parameter The parameter to set
	 * @param string $value The value of the parameter
	 *
	 * @example, for mssqlnative driver ('CharacterSet','UTF-8')
	 * @return bool
	 */
	public function setConnectionParameter($parameter, $value) {
		if(!is_numeric($parameter)) {
			$this->outp_throw("Invalid connection parameter '$parameter'", __METHOD__);
			return false;
		}
		$this->connectionParameters[$parameter] = $value;
		return true;
	}

	/**
	 * Connect to a database.
	 *
	 * @todo add: parameter int $port, parameter string $socket
	 *
	 * @param string|null $argHostname (Optional) The host to connect to.
	 * @param string|null $argUsername (Optional) The username to connect as.
	 * @param string|null $argPassword (Optional) The password to connect with.
	 * @param string|null $argDatabasename (Optional) The name of the database to start in when connected.
	 * @param bool $persist (Optional) Whether or not to use a persistent connection.
	 *
	 * @return bool|null True if connected successfully, false if connection failed, or null if the mysqli extension
	 * isn't currently loaded.
	 */
	function _connect($argHostname = null,
					  $argUsername = null,
					  $argPassword = null,
					  $argDatabasename = null,
					  $persist = false)
	{
		if(!extension_loaded("mysqli")) {
			return null;
		}
		$this->_connectionID = @mysqli_init();

		if (is_null($this->_connectionID)) {
			// mysqli_init only fails if insufficient memory
			if ($this->debug) {
				ADOConnection::outp("mysqli_init() failed : "  . $this->errorMsg());
			}
			return false;
		}
		/*
		I suggest a simple fix which would enable adodb and mysqli driver to
		read connection options from the standard mysql configuration file
		/etc/my.cnf - "Bastien Duclaux" <bduclaux#yahoo.com>
		*/
		$this->optionFlags = array();
		foreach($this->optionFlags as $arr) {
			mysqli_options($this->_connectionID,$arr[0],$arr[1]);
		}

		// Now merge in the standard connection parameters setting
		foreach ($this->connectionParameters as $parameter => $value) {
			// Make sure parameter is numeric before calling mysqli_options()
			// that to avoid Warning (or TypeError exception on PHP 8).
			if (!is_numeric($parameter)
				|| !mysqli_options($this->_connectionID, $parameter, $value)
			) {
				$this->outp_throw("Invalid connection parameter '$parameter'", __METHOD__);
			}
		}

		//https://php.net/manual/en/mysqli.persistconns.php
		if ($persist && strncmp($argHostname,'p:',2) != 0) {
			$argHostname = 'p:' . $argHostname;
		}

		// SSL Connections for MySQLI
		if ($this->ssl_key || $this->ssl_cert || $this->ssl_ca || $this->ssl_capath || $this->ssl_cipher) {
			mysqli_ssl_set($this->_connectionID, $this->ssl_key, $this->ssl_cert, $this->ssl_ca, $this->ssl_capath, $this->ssl_cipher);
		}

		#if (!empty($this->port)) $argHostname .= ":".$this->port;
		$ok = @mysqli_real_connect($this->_connectionID,
					$argHostname,
					$argUsername,
					$argPassword,
					$argDatabasename,
					# PHP7 compat: port must be int. Use default port if cast yields zero
					(int)$this->port != 0 ? (int)$this->port : 3306,
					$this->socket,
					$this->clientFlags);

		if ($ok) {
			if ($argDatabasename)  return $this->selectDB($argDatabasename);
			return true;
		} else {
			if ($this->debug) {
				ADOConnection::outp("Could not connect : "  . $this->errorMsg());
			}
			$this->_connectionID = null;
			return false;
		}
	}

	/**
	 * Connect to a database with a persistent connection.
	 *
	 * @param string|null $argHostname The host to connect to.
	 * @param string|null $argUsername The username to connect as.
	 * @param string|null $argPassword The password to connect with.
	 * @param string|null $argDatabasename The name of the database to start in when connected.
	 *
	 * @return bool|null True if connected successfully, false if connection failed, or null if the mysqli extension
	 * isn't currently loaded.
	 */
	function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
	{
		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, true);
	}

	/**
	 * Connect to a database, whilst setting $this->forceNewConnect to true.
	 *
	 * When is this used? Close old connection first?
	 * In _connect(), check $this->forceNewConnect?
	 *
	 * @param string|null $argHostname The host to connect to.
	 * @param string|null $argUsername The username to connect as.
	 * @param string|null $argPassword The password to connect with.
	 * @param string|null $argDatabasename The name of the database to start in when connected.
	 *
	 * @return bool|null True if connected successfully, false if connection failed, or null if the mysqli extension
	 * isn't currently loaded.
	 */
	function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
	{
		$this->forceNewConnect = true;
		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
	}

	/**
	 * Replaces a null value with a specified replacement.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:ifnull
	 *
	 * @param mixed $field The field in the table to check.
	 * @param mixed $ifNull The value to replace the null value with if it is found.
	 *
	 * @return string
	 */
	function IfNull($field, $ifNull)
	{
		return " IFNULL($field, $ifNull) ";
	}

	/**
	 * Retrieves the first column of the first matching row of an executed SQL statement.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:getone
	 *
	 * @param string $sql The SQL to execute.
	 * @param bool|array $inputarr (Optional) An array containing any required SQL parameters, or false if none needed.
	 *
	 * @return bool|array|null
	 */
	function GetOne($sql, $inputarr = false)
	{
		global $ADODB_GETONE_EOF;

		$ret = false;
		$rs = $this->execute($sql,$inputarr);
		if ($rs) {
			if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
			else $ret = reset($rs->fields);
			$rs->close();
		}
		return $ret;
	}

	/**
	 * Get information about the current MySQL server.
	 *
	 * @return array
	 */
	function ServerInfo()
	{
		$arr['description'] = $this->getOne("select version()");
		$arr['version'] = ADOConnection::_findvers($arr['description']);
		return $arr;
	}

	/**
	 * Begins a granular transaction.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:begintrans
	 *
	 * @return bool Always returns true.
	 */
	function BeginTrans()
	{
		if ($this->transOff) return true;
		$this->transCnt += 1;

		//$this->execute('SET AUTOCOMMIT=0');
		mysqli_autocommit($this->_connectionID, false);
		$this->execute('BEGIN');
		return true;
	}

	/**
	 * Commits a granular transaction.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:committrans
	 *
	 * @param bool $ok (Optional) If false, will rollback the transaction instead.
	 *
	 * @return bool Always returns true.
	 */
	function CommitTrans($ok = true)
	{
		if ($this->transOff) return true;
		if (!$ok) return $this->rollbackTrans();

		if ($this->transCnt) $this->transCnt -= 1;
		$this->execute('COMMIT');

		//$this->execute('SET AUTOCOMMIT=1');
		mysqli_autocommit($this->_connectionID, true);
		return true;
	}

	/**
	 * Rollback a smart transaction.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:rollbacktrans
	 *
	 * @return bool Always returns true.
	 */
	function RollbackTrans()
	{
		if ($this->transOff) return true;
		if ($this->transCnt) $this->transCnt -= 1;
		$this->execute('ROLLBACK');
		//$this->execute('SET AUTOCOMMIT=1');
		mysqli_autocommit($this->_connectionID, true);
		return true;
	}

	/**
	 * Lock a table row for a duration of a transaction.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:rowlock
	 *
	 * @param string $tables The table(s) to lock rows for.
	 * @param string $where (Optional) The WHERE clause to use to determine which rows to lock.
	 * @param string $col (Optional) The columns to select.
	 *
	 * @return bool True if the locking SQL statement executed successfully, otherwise false.
	 */
	function RowLock($tables, $where = '', $col = '1 as adodbignore')
	{
		if ($this->transCnt==0) $this->beginTrans();
		if ($where) $where = ' where '.$where;
		$rs = $this->execute("select $col from $tables $where for update");
		return !empty($rs);
	}

	/**
	 * Appropriately quotes strings with ' characters for insertion into the database.
	 *
	 * Relies on mysqli_real_escape_string()
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:qstr
	 *
	 * @param string $s            The string to quote
	 * @param bool   $magic_quotes This param is not used since 5.21.0.
	 *                             It remains for backwards compatibility.
	 *
	 * @return string Quoted string
	 */
	function qStr($s, $magic_quotes=false)
	{
		if (is_null($s)) {
			return 'NULL';
		}

		// mysqli_real_escape_string() throws a warning when the given
		// connection is invalid
		if ($this->_connectionID) {
			return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'";
		}

		if ($this->replaceQuote[0] == '\\') {
			$s = str_replace(array('\\', "\0"), array('\\\\', "\\\0") ,$s);
		}
		return "'" . str_replace("'", $this->replaceQuote, $s) . "'";
	}

	/**
	 * Return the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.
	 *
	 * @inheritDoc
	 */
	protected function _insertID($table = '', $column = '')
	{
		// mysqli_insert_id does not return the last_insert_id if called after
		// execution of a stored procedure so we execute this instead.
		if ($this->useLastInsertStatement)
			$result = ADOConnection::getOne('SELECT LAST_INSERT_ID()');
		else
			$result = @mysqli_insert_id($this->_connectionID);

		if ($result == -1) {
			if ($this->debug)
				ADOConnection::outp("mysqli_insert_id() failed : "  . $this->errorMsg());
		}
		// reset prepared statement flags
		$this->usePreparedStatement   = false;
		$this->useLastInsertStatement = false;
		return $result;
	}

	/**
	 * Returns how many rows were effected by the most recently executed SQL statement.
	 * Only works for INSERT, UPDATE and DELETE queries.
	 *
	 * @return int The number of rows affected.
	 */
	function _affectedrows()
	{
		if ($this->isSelectStatement) {
			// Affected rows works fine against selects, returning
			// the rowcount, but ADOdb does not do that.
			return false;
		}

		$result =  @mysqli_affected_rows($this->_connectionID);
		if ($result == -1) {
			if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : "  . $this->errorMsg());
		}
		return $result;
	}

	// Reference on Last_Insert_ID on the recommended way to simulate sequences
	var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
	var $_genSeqSQL = "create table if not exists %s (id int not null)";
	var $_genSeqCountSQL = "select count(*) from %s";
	var $_genSeq2SQL = "insert into %s values (%s)";
	var $_dropSeqSQL = "drop table if exists %s";

	/**
	 * Creates a sequence in the database.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:createsequence
	 *
	 * @param string $seqname The sequence name.
	 * @param int $startID The start id.
	 *
	 * @return ADORecordSet|bool A record set if executed successfully, otherwise false.
	 */
	function CreateSequence($seqname = 'adodbseq', $startID = 1)
	{
		if (empty($this->_genSeqSQL)) return false;

		$ok = $this->execute(sprintf($this->_genSeqSQL,$seqname));
		if (!$ok) return false;
		return $this->execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
	}

	/**
	 * A portable method of creating sequence numbers.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:genid
	 *
	 * @param string $seqname (Optional) The name of the sequence to use.
	 * @param int $startID (Optional) The point to start at in the sequence.
	 *
	 * @return bool|int|string
	 */
	function GenID($seqname = 'adodbseq', $startID = 1)
	{
		// post-nuke sets hasGenID to false
		if (!$this->hasGenID) return false;

		$getnext = sprintf($this->_genIDSQL,$seqname);
		$holdtransOK = $this->_transOK; // save the current status
		$rs = @$this->execute($getnext);
		if (!$rs) {
			if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
			$this->execute(sprintf($this->_genSeqSQL,$seqname));
			$cnt = $this->getOne(sprintf($this->_genSeqCountSQL,$seqname));
			if (!$cnt) $this->execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
			$rs = $this->execute($getnext);
		}

		if ($rs) {
			$this->genID = mysqli_insert_id($this->_connectionID);
			if ($this->genID == 0) {
				$getnext = "select LAST_INSERT_ID() from " . $seqname;
				$rs = $this->execute($getnext);
				$this->genID = (int)$rs->fields[0];
			}
			$rs->close();
		} else
			$this->genID = 0;

		return $this->genID;
	}

	/**
	 * Return a list of all visible databases except the 'mysql' database.
	 *
	 * @return array|false An array of database names, or false if the query failed.
	 */
	function MetaDatabases()
	{
		$query = "SHOW DATABASES";
		$ret = $this->execute($query);
		if ($ret && is_object($ret)){
			$arr = array();
			while (!$ret->EOF){
				$db = $ret->fields('Database');
				if ($db != 'mysql') $arr[] = $db;
				$ret->moveNext();
			}
			return $arr;
		}
		return $ret;
	}

	/**
	 * Get a list of indexes on the specified table.
	 *
	 * @param string $table The name of the table to get indexes for.
	 * @param bool $primary (Optional) Whether or not to include the primary key.
	 * @param bool $owner (Optional) Unused.
	 *
	 * @return array|bool An array of the indexes, or false if the query to get the indexes failed.
	 */
	function MetaIndexes($table, $primary = false, $owner = false)
	{
		// save old fetch mode
		global $ADODB_FETCH_MODE;

		$false = false;
		$save = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
		if ($this->fetchMode !== FALSE) {
			$savem = $this->setFetchMode(FALSE);
		}

		// get index details
		$rs = $this->execute(sprintf('SHOW INDEXES FROM %s',$table));

		// restore fetchmode
		if (isset($savem)) {
			$this->setFetchMode($savem);
		}
		$ADODB_FETCH_MODE = $save;

		if (!is_object($rs)) {
			return $false;
		}

		$indexes = array ();

		// parse index data into array
		while ($row = $rs->fetchRow()) {
			if ($primary == FALSE AND $row[2] == 'PRIMARY') {
				continue;
			}

			if (!isset($indexes[$row[2]])) {
				$indexes[$row[2]] = array(
					'unique' => ($row[1] == 0),
					'columns' => array()
				);
			}

			$indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
		}

		// sort columns by order in the index
		foreach ( array_keys ($indexes) as $index )
		{
			ksort ($indexes[$index]['columns']);
		}

		return $indexes;
	}

	/**
	 * Returns a portably-formatted date string from a timestamp database column.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:sqldate
	 *
	 * @param string $fmt The date format to use.
	 * @param string|bool $col (Optional) The table column to date format, or if false, use NOW().
	 *
	 * @return bool|string The SQL DATE_FORMAT() string, or false if the provided date format was empty.
	 */
	function SQLDate($fmt, $col = false)
	{
		if (!$col) $col = $this->sysTimeStamp;
		$s = 'DATE_FORMAT('.$col.",'";
		$concat = false;
		$len = strlen($fmt);
		for ($i=0; $i < $len; $i++) {
			$ch = $fmt[$i];
			switch($ch) {
			case 'Y':
			case 'y':
				$s .= '%Y';
				break;
			case 'Q':
			case 'q':
				$s .= "'),Quarter($col)";

				if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
				else $s .= ",('";
				$concat = true;
				break;
			case 'M':
				$s .= '%b';
				break;

			case 'm':
				$s .= '%m';
				break;
			case 'D':
			case 'd':
				$s .= '%d';
				break;

			case 'H':
				$s .= '%H';
				break;

			case 'h':
				$s .= '%I';
				break;

			case 'i':
				$s .= '%i';
				break;

			case 's':
				$s .= '%s';
				break;

			case 'a':
			case 'A':
				$s .= '%p';
				break;

			case 'w':
				$s .= '%w';
				break;

			case 'l':
				$s .= '%W';
				break;

			default:

				if ($ch == '\\') {
					$i++;
					$ch = substr($fmt,$i,1);
				}
				$s .= $ch;
				break;
			}
		}
		$s.="')";
		if ($concat) $s = "CONCAT($s)";
		return $s;
	}

	/**
	 * Returns a database-specific concatenation of strings.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:concat
	 *
	 * @return string
	 */
	function Concat()
	{
		$arr = func_get_args();

		// suggestion by andrew005@mnogo.ru
		$s = implode(',',$arr);
		if (strlen($s) > 0) return "CONCAT($s)";
		else return '';
	}

	/**
	 * Creates a portable date offset field, for use in SQL statements.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:offsetdate
	 *
	 * @param float $dayFraction A day in floating point
	 * @param string|bool $date (Optional) The date to offset. If false, uses CURDATE()
	 *
	 * @return string
	 */
	function OffsetDate($dayFraction, $date = false)
	{
		if (!$date) $date = $this->sysDate;

		$fraction = $dayFraction * 24 * 3600;
		return $date . ' + INTERVAL ' .	 $fraction.' SECOND';

//		return "from_unixtime(unix_timestamp($date)+$fraction)";
	}

	/**
	 * Returns information about stored procedures and stored functions.
	 *
	 * @param string|bool $NamePattern (Optional) Only look for procedures/functions with a name matching this pattern.
	 * @param null $catalog (Optional) Unused.
	 * @param null $schemaPattern (Optional) Unused.
	 *
	 * @return array
	 */
	function MetaProcedures($NamePattern = false, $catalog  = null, $schemaPattern  = null)
	{
		// save old fetch mode
		global $ADODB_FETCH_MODE;

		$save = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;

		if ($this->fetchMode !== FALSE) {
			$savem = $this->setFetchMode(FALSE);
		}

		$procedures = array ();

		// get index details

		$likepattern = '';
		if ($NamePattern) {
			$likepattern = " LIKE '".$NamePattern."'";
		}
		$rs = $this->execute('SHOW PROCEDURE STATUS'.$likepattern);
		if (is_object($rs)) {

			// parse index data into array
			while ($row = $rs->fetchRow()) {
				$procedures[$row[1]] = array(
					'type' => 'PROCEDURE',
					'catalog' => '',
					'schema' => '',
					'remarks' => $row[7],
				);
			}
		}

		$rs = $this->execute('SHOW FUNCTION STATUS'.$likepattern);
		if (is_object($rs)) {
			// parse index data into array
			while ($row = $rs->fetchRow()) {
				$procedures[$row[1]] = array(
					'type' => 'FUNCTION',
					'catalog' => '',
					'schema' => '',
					'remarks' => $row[7]
				);
			}
		}

		// restore fetchmode
		if (isset($savem)) {
				$this->setFetchMode($savem);
		}
		$ADODB_FETCH_MODE = $save;

		return $procedures;
	}

	/**
	 * Retrieves a list of tables based on given criteria
	 *
	 * @param string|bool $ttype (Optional) Table type = 'TABLE', 'VIEW' or false=both (default)
	 * @param string|bool $showSchema (Optional) schema name, false = current schema (default)
	 * @param string|bool $mask (Optional) filters the table by name
	 *
	 * @return array list of tables
	 */
	function MetaTables($ttype = false, $showSchema = false, $mask = false)
	{
		$save = $this->metaTablesSQL;
		if ($showSchema && is_string($showSchema)) {
			$this->metaTablesSQL .= $this->qstr($showSchema);
		} else {
			$this->metaTablesSQL .= "schema()";
		}

		if ($mask) {
			$mask = $this->qstr($mask);
			$this->metaTablesSQL .= " AND table_name LIKE $mask";
		}
		$ret = ADOConnection::metaTables($ttype,$showSchema);

		$this->metaTablesSQL = $save;
		return $ret;
	}

	/**
	 * Return information about a table's foreign keys.
	 *
	 * @param string $table The name of the table to get the foreign keys for.
	 * @param string|bool $owner (Optional) The database the table belongs to, or false to assume the current db.
	 * @param string|bool $upper (Optional) Force uppercase table name on returned array keys.
	 * @param bool $associative (Optional) Whether to return an associate or numeric array.
	 *
	 * @return array|bool An array of foreign keys, or false no foreign keys could be found.
	 */
	function MetaForeignKeys($table, $owner = false, $upper = false, $associative = false)
	{

		global $ADODB_FETCH_MODE;

		if ($ADODB_FETCH_MODE == ADODB_FETCH_ASSOC
		|| $this->fetchMode == ADODB_FETCH_ASSOC)
			$associative = true;

		$savem = $ADODB_FETCH_MODE;
		$this->setFetchMode(ADODB_FETCH_ASSOC);

		if ( !empty($owner) ) {
			$table = "$owner.$table";
		}

		$a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));

		$this->setFetchMode($savem);

		$create_sql = isset($a_create_table["Create Table"]) ? $a_create_table["Create Table"] : $a_create_table["Create View"];

		$matches = array();

		if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
		$foreign_keys = array();
		$num_keys = count($matches[0]);
		for ( $i = 0; $i < $num_keys; $i ++ ) {
			$my_field  = explode('`, `', $matches[1][$i]);
			$ref_table = $matches[2][$i];
			$ref_field = explode('`, `', $matches[3][$i]);

			if ( $upper ) {
				$ref_table = strtoupper($ref_table);
			}

			// see https://sourceforge.net/p/adodb/bugs/100/
			if (!isset($foreign_keys[$ref_table])) {
				$foreign_keys[$ref_table] = array();
			}
			$num_fields = count($my_field);
			for ( $j = 0; $j < $num_fields; $j ++ ) {
				if ( $associative ) {
					$foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
				} else {
					$foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
				}
			}
		}

		return $foreign_keys;
	}

	/**
	 * Return an array of information about a table's columns.
	 *
	 * @param string $table The name of the table to get the column info for.
	 * @param bool $normalize (Optional) Unused.
	 *
	 * @return ADOFieldObject[]|bool An array of info for each column, or false if it could not determine the info.
	 */
	function MetaColumns($table, $normalize = true)
	{
		$false = false;
		if (!$this->metaColumnsSQL)
			return $false;

		global $ADODB_FETCH_MODE;
		$save = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
		if ($this->fetchMode !== false)
			$savem = $this->SetFetchMode(false);
		/*
		* Return assoc array where key is column name, value is column type
		*    [1] => int unsigned
		*/

		$SQL = "SELECT column_name, column_type
				  FROM information_schema.columns
				 WHERE table_schema='{$this->databaseName}'
				   AND table_name='$table'";

		$schemaArray = $this->getAssoc($SQL);
		$schemaArray = array_change_key_case($schemaArray,CASE_LOWER);

		$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
		if (isset($savem)) $this->SetFetchMode($savem);
		$ADODB_FETCH_MODE = $save;
		if (!is_object($rs))
			return $false;

		$retarr = array();
		while (!$rs->EOF) {
			$fld = new ADOFieldObject();
			$fld->name = $rs->fields[0];
			$type = $rs->fields[1];

			/*
			* Type from information_schema returns
			* the same format in V8 mysql as V5
			*/
			$type = $schemaArray[strtolower($fld->name)];

			// split type into type(length):
			$fld->scale = null;
			if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
				$fld->type = $query_array[1];
				$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
				$fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
			} elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
				$fld->type = $query_array[1];
				$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
			} elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) {
				$fld->type = $query_array[1];
				$arr = explode(",",$query_array[2]);
				$fld->enums = $arr;
				$zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6
				$fld->max_length = ($zlen > 0) ? $zlen : 1;
			} else {
				$fld->type = $type;
				$fld->max_length = -1;
			}

			$fld->not_null = ($rs->fields[2] != 'YES');
			$fld->primary_key = ($rs->fields[3] == 'PRI');
			$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
			$fld->binary = (strpos($type,'blob') !== false);
			$fld->unsigned = (strpos($type,'unsigned') !== false);
			$fld->zerofill = (strpos($type,'zerofill') !== false);

			if (!$fld->binary) {
				$d = $rs->fields[4];
				if ($d != '' && $d != 'NULL') {
					$fld->has_default = true;
					$fld->default_value = $d;
				} else {
					$fld->has_default = false;
				}
			}

			if ($save == ADODB_FETCH_NUM) {
				$retarr[] = $fld;
			} else {
				$retarr[strtoupper($fld->name)] = $fld;
			}
			$rs->moveNext();
		}

		$rs->close();
		return $retarr;
	}

	/**
	 * Select which database to connect to.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:selectdb
	 *
	 * @param string $dbName The name of the database to select.
	 *
	 * @return bool True if the database was selected successfully, otherwise false.
	 */
	function SelectDB($dbName)
	{
//		$this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
		$this->database = $dbName;
		$this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions

		if ($this->_connectionID) {
			$result = @mysqli_select_db($this->_connectionID, $dbName);
			if (!$result) {
				ADOConnection::outp("Select of database " . $dbName . " failed. " . $this->errorMsg());
			}
			return $result;
		}
		return false;
	}

	/**
	 * Executes a provided SQL statement and returns a handle to the result, with the ability to supply a starting
	 * offset and record count.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:selectlimit
	 *
	 * @param string $sql The SQL to execute.
	 * @param int $nrows (Optional) The limit for the number of records you want returned. By default, all results.
	 * @param int $offset (Optional) The offset to use when selecting the results. By default, no offset.
	 * @param array|bool $inputarr (Optional) Any parameter values required by the SQL statement, or false if none.
	 * @param int $secs (Optional) If greater than 0, perform a cached execute. By default, normal execution.
	 *
	 * @return ADORecordSet|false The query results, or false if the query failed to execute.
	 */
	function SelectLimit($sql,
						 $nrows = -1,
						 $offset = -1,
						 $inputarr = false,
						 $secs = 0)
	{
		$nrows = (int) $nrows;
		$offset = (int) $offset;
		$offsetStr = ($offset >= 0) ? "$offset," : '';
		if ($nrows < 0) $nrows = '18446744073709551615';

		if ($secs)
			$rs = $this->cacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr );
		else
			$rs = $this->execute($sql . " LIMIT $offsetStr$nrows" , $inputarr );

		return $rs;
	}

	/**
	 * Prepares an SQL statement and returns a handle to use.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:prepare
	 * @todo update this function to handle prepared statements correctly
	 *
	 * @param string $sql The SQL to prepare.
	 *
	 * @return string The original SQL that was provided.
	 */
	function Prepare($sql)
	{
		/*
		* Flag the insert_id method to use the correct retrieval method
		*/
		$this->usePreparedStatement = true;

		/*
		* Prepared statements are not yet handled correctly
		*/
		return $sql;
		$stmt = $this->_connectionID->prepare($sql);
		if (!$stmt) {
			echo $this->errorMsg();
			return $sql;
		}
		return array($sql,$stmt);
	}

	/**
	 * Return the query id.
	 *
	 * @param string|array $sql
	 * @param array $inputarr
	 *
	 * @return bool|mysqli_result
	 */
	function _query($sql, $inputarr)
	{
		global $ADODB_COUNTRECS;
		// Move to the next recordset, or return false if there is none. In a stored proc
		// call, mysqli_next_result returns true for the last "recordset", but mysqli_store_result
		// returns false. I think this is because the last "recordset" is actually just the
		// return value of the stored proc (ie the number of rows affected).
		// Commented out for reasons of performance. You should retrieve every recordset yourself.
		//	if (!mysqli_next_result($this->connection->_connectionID))	return false;

		if (is_array($sql)) {

			// Prepare() not supported because mysqli_stmt_execute does not return a recordset, but
			// returns as bound variables.

			$stmt = $sql[1];
			$a = '';
			foreach($inputarr as $k => $v) {
				if (is_string($v)) $a .= 's';
				else if (is_integer($v)) $a .= 'i';
				else $a .= 'd';
			}

			/*
			 * set prepared statement flags
			 */
			if ($this->usePreparedStatement)
				$this->useLastInsertStatement = true;

			$fnarr = array_merge( array($stmt,$a) , $inputarr);
			call_user_func_array('mysqli_stmt_bind_param',$fnarr);
			$ret = mysqli_stmt_execute($stmt);
			return $ret;
		}
		else
		{
			/*
			* reset prepared statement flags, in case we set them
			* previously and didn't use them
			*/
			$this->usePreparedStatement   = false;
			$this->useLastInsertStatement = false;
		}

		/*
		if (!$mysql_res =  mysqli_query($this->_connectionID, $sql, ($ADODB_COUNTRECS) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT)) {
			if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->errorMsg());
			return false;
		}

		return $mysql_res;
		*/

		if ($this->multiQuery) {
			$rs = mysqli_multi_query($this->_connectionID, $sql.';');
			if ($rs) {
				$rs = ($ADODB_COUNTRECS) ? @mysqli_store_result( $this->_connectionID ) : @mysqli_use_result( $this->_connectionID );
				return $rs ? $rs : true; // mysqli_more_results( $this->_connectionID )
			}
		} else {
			$rs = mysqli_query($this->_connectionID, $sql, $ADODB_COUNTRECS ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT);
			if ($rs) {
				$this->isSelectStatement = is_object($rs);
				return $rs;
			}
		}

		if($this->debug)
			ADOConnection::outp("Query: " . $sql . " failed. " . $this->errorMsg());

		return false;

	}

	/**
	 * Returns a database specific error message.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:errormsg
	 *
	 * @return string The last error message.
	 */
	function ErrorMsg()
	{
		if (empty($this->_connectionID))
			$this->_errorMsg = @mysqli_connect_error();
		else
			$this->_errorMsg = @mysqli_error($this->_connectionID);
		return $this->_errorMsg;
	}

	/**
	 * Returns the last error number from previous database operation.
	 *
	 * @return int The last error number.
	 */
	function ErrorNo()
	{
		if (empty($this->_connectionID))
			return @mysqli_connect_errno();
		else
			return @mysqli_errno($this->_connectionID);
	}

	/**
	 * Close the database connection.
	 *
	 * @return void
	 */
	function _close()
	{
		if($this->_connectionID) {
			mysqli_close($this->_connectionID);
		}
		$this->_connectionID = false;
	}

	/**
	 * Returns the largest length of data that can be inserted into a character field.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:charmax
	 *
	 * @return int
	 */
	function CharMax()
	{
		return 255;
	}

	/**
	 * Returns the largest length of data that can be inserted into a text field.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:textmax
	 *
	 * @return int
	 */
	function TextMax()
	{
		return 4294967295;
	}

	function getCharSet()
	{
		if (!$this->_connectionID || !method_exists($this->_connectionID,'character_set_name')) {
			return false;
		}

		$this->charSet = $this->_connectionID->character_set_name();
		return $this->charSet ?: false;
	}

	function setCharSet($charset)
	{
		if (!$this->_connectionID || !method_exists($this->_connectionID,'set_charset')) {
			return false;
		}

		if ($this->charSet !== $charset) {
			if (!$this->_connectionID->set_charset($charset)) {
				return false;
			}
			$this->getCharSet();
		}
		return true;
	}

}

/**
 * Class ADORecordSet_mysqli
 */
class ADORecordSet_mysqli extends ADORecordSet{

	var $databaseType = "mysqli";
	var $canSeek = true;

	function __construct($queryID, $mode = false)
	{
		if ($mode === false) {
			global $ADODB_FETCH_MODE;
			$mode = $ADODB_FETCH_MODE;
		}

		switch ($mode) {
			case ADODB_FETCH_NUM:
				$this->fetchMode = MYSQLI_NUM;
				break;
			case ADODB_FETCH_ASSOC:
				$this->fetchMode = MYSQLI_ASSOC;
				break;
			case ADODB_FETCH_DEFAULT:
			case ADODB_FETCH_BOTH:
			default:
				$this->fetchMode = MYSQLI_BOTH;
				break;
		}
		$this->adodbFetchMode = $mode;
		parent::__construct($queryID);
	}

	function _initrs()
	{
	global $ADODB_COUNTRECS;

		$this->_numOfRows = $ADODB_COUNTRECS ? @mysqli_num_rows($this->_queryID) : -1;
		$this->_numOfFields = @mysqli_num_fields($this->_queryID);
	}

/*
1      = MYSQLI_NOT_NULL_FLAG
2      = MYSQLI_PRI_KEY_FLAG
4      = MYSQLI_UNIQUE_KEY_FLAG
8      = MYSQLI_MULTIPLE_KEY_FLAG
16     = MYSQLI_BLOB_FLAG
32     = MYSQLI_UNSIGNED_FLAG
64     = MYSQLI_ZEROFILL_FLAG
128    = MYSQLI_BINARY_FLAG
256    = MYSQLI_ENUM_FLAG
512    = MYSQLI_AUTO_INCREMENT_FLAG
1024   = MYSQLI_TIMESTAMP_FLAG
2048   = MYSQLI_SET_FLAG
32768  = MYSQLI_NUM_FLAG
16384  = MYSQLI_PART_KEY_FLAG
32768  = MYSQLI_GROUP_FLAG
65536  = MYSQLI_UNIQUE_FLAG
131072 = MYSQLI_BINCMP_FLAG
*/

	/**
	 * Returns raw, database specific information about a field.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:recordset:fetchfield
	 *
	 * @param int $fieldOffset (Optional) The field number to get information for.
	 *
	 * @return ADOFieldObject|bool
	 */
	function FetchField($fieldOffset = -1)
	{
		$fieldnr = $fieldOffset;
		if ($fieldOffset != -1) {
			$fieldOffset = @mysqli_field_seek($this->_queryID, $fieldnr);
		}
		$o = @mysqli_fetch_field($this->_queryID);
		if (!$o) return false;

		//Fix for HHVM
		if ( !isset($o->flags) ) {
			$o->flags = 0;
		}
		/* Properties of an ADOFieldObject as set by MetaColumns */
		$o->primary_key = $o->flags & MYSQLI_PRI_KEY_FLAG;
		$o->not_null = $o->flags & MYSQLI_NOT_NULL_FLAG;
		$o->auto_increment = $o->flags & MYSQLI_AUTO_INCREMENT_FLAG;
		$o->binary = $o->flags & MYSQLI_BINARY_FLAG;
		// $o->blob = $o->flags & MYSQLI_BLOB_FLAG; /* not returned by MetaColumns */
		$o->unsigned = $o->flags & MYSQLI_UNSIGNED_FLAG;

		/*
		* Trivial method to cast class to ADOfieldObject
		*/
		$a = new ADOFieldObject;
		foreach (get_object_vars($o) as $key => $name)
			$a->$key = $name;
		return $a;
	}

	/**
	 * Reads a row in associative mode if the recordset fetch mode is numeric.
	 * Using this function when the fetch mode is set to ADODB_FETCH_ASSOC may produce unpredictable results.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:getrowassoc
	 *
	 * @param int $upper Indicates whether the keys of the recordset should be upper case or lower case.
	 *
	 * @return array|bool
	 */
	function GetRowAssoc($upper = ADODB_ASSOC_CASE)
	{
		if ($this->fetchMode == MYSQLI_ASSOC && $upper == ADODB_ASSOC_CASE_LOWER) {
			return $this->fields;
		}
		$row = ADORecordSet::getRowAssoc($upper);
		return $row;
	}

	/**
	 * Returns a single field in a single row of the current recordset.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:recordset:fields
	 *
	 * @param string $colname The name of the field to retrieve.
	 *
	 * @return mixed
	 */
	function Fields($colname)
	{
		if ($this->fetchMode != MYSQLI_NUM) {
			return @$this->fields[$colname];
		}

		if (!$this->bind) {
			$this->bind = array();
			for ($i = 0; $i < $this->_numOfFields; $i++) {
				$o = $this->fetchField($i);
				$this->bind[strtoupper($o->name)] = $i;
			}
		}
		return $this->fields[$this->bind[strtoupper($colname)]];
	}

	/**
	 * Adjusts the result pointer to an arbitrary row in the result.
	 *
	 * @param int $row The row to seek to.
	 *
	 * @return bool False if the recordset contains no rows, otherwise true.
	 */
	function _seek($row)
	{
		if ($this->_numOfRows == 0 || $row < 0) {
			return false;
		}

		mysqli_data_seek($this->_queryID, $row);
		$this->EOF = false;
		return true;
	}

	/**
	 * In databases that allow accessing of recordsets, retrieves the next set.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:recordset:nextrecordset
	 *
	 * @return bool
	 */
	function NextRecordSet()
	{
		global $ADODB_COUNTRECS;

		mysqli_free_result($this->_queryID);
		$this->_queryID = -1;
		// Move to the next recordset, or return false if there is none. In a stored proc
		// call, mysqli_next_result returns true for the last "recordset", but mysqli_store_result
		// returns false. I think this is because the last "recordset" is actually just the
		// return value of the stored proc (ie the number of rows affected).
		if (!mysqli_next_result($this->connection->_connectionID)) {
			return false;
		}

		// CD: There is no $this->_connectionID variable, at least in the ADO version I'm using
		$this->_queryID = ($ADODB_COUNTRECS) ? @mysqli_store_result($this->connection->_connectionID)
			: @mysqli_use_result($this->connection->_connectionID);

		if (!$this->_queryID) {
			return false;
		}

		$this->_inited     = false;
		$this->bind        = false;
		$this->_currentRow = -1;
		$this->init();
		return true;
	}

	/**
	 * Moves the cursor to the next record of the recordset from the current position.
	 *
	 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:movenext
	 *
	 * @return bool False if there are no more records to move on to, otherwise true.
	 */
	function MoveNext()
	{
		if ($this->EOF) return false;
		$this->_currentRow++;
		$this->fields = @mysqli_fetch_array($this->_queryID,$this->fetchMode);

		if (is_array($this->fields)) {
			$this->_updatefields();
			return true;
		}
		$this->EOF = true;
		return false;
	}

	/**
	 * Attempt to fetch a result row using the current fetch mode and return whether or not this was successful.
	 *
	 * @return bool True if row was fetched successfully, otherwise false.
	 */
	function _fetch()
	{
		$this->fields = mysqli_fetch_array($this->_queryID,$this->fetchMode);
		$this->_updatefields();
		return is_array($this->fields);
	}

	/**
	 * Frees the memory associated with a result.
	 *
	 * @return void
	 */
	function _close()
	{
		//if results are attached to this pointer from Stored Procedure calls, the next standard query will die 2014
		//only a problem with persistent connections

		if (isset($this->connection->_connectionID) && $this->connection->_connectionID) {
			while (mysqli_more_results($this->connection->_connectionID)) {
				mysqli_next_result($this->connection->_connectionID);
			}
		}

		if ($this->_queryID instanceof mysqli_result) {
			mysqli_free_result($this->_queryID);
		}
		$this->_queryID = false;
	}

/*

0 = MYSQLI_TYPE_DECIMAL
1 = MYSQLI_TYPE_CHAR
1 = MYSQLI_TYPE_TINY
2 = MYSQLI_TYPE_SHORT
3 = MYSQLI_TYPE_LONG
4 = MYSQLI_TYPE_FLOAT
5 = MYSQLI_TYPE_DOUBLE
6 = MYSQLI_TYPE_NULL
7 = MYSQLI_TYPE_TIMESTAMP
8 = MYSQLI_TYPE_LONGLONG
9 = MYSQLI_TYPE_INT24
10 = MYSQLI_TYPE_DATE
11 = MYSQLI_TYPE_TIME
12 = MYSQLI_TYPE_DATETIME
13 = MYSQLI_TYPE_YEAR
14 = MYSQLI_TYPE_NEWDATE
247 = MYSQLI_TYPE_ENUM
248 = MYSQLI_TYPE_SET
249 = MYSQLI_TYPE_TINY_BLOB
250 = MYSQLI_TYPE_MEDIUM_BLOB
251 = MYSQLI_TYPE_LONG_BLOB
252 = MYSQLI_TYPE_BLOB
253 = MYSQLI_TYPE_VAR_STRING
254 = MYSQLI_TYPE_STRING
255 = MYSQLI_TYPE_GEOMETRY
*/

	/**
	 * Get the MetaType character for a given field type.
	 *
	 * @param string|object $t The type to get the MetaType character for.
	 * @param int $len (Optional) Redundant. Will always be set to -1.
	 * @param bool|object $fieldobj (Optional)
	 *
	 * @return string The MetaType
	 */
	function MetaType($t, $len = -1, $fieldobj = false)
	{
		if (is_object($t)) {
			$fieldobj = $t;
			$t = $fieldobj->type;
			$len = $fieldobj->max_length;
		}

		$len = -1; // mysql max_length is not accurate
		switch (strtoupper($t)) {
			case 'STRING':
			case 'CHAR':
			case 'VARCHAR':
			case 'TINYBLOB':
			case 'TINYTEXT':
			case 'ENUM':
			case 'SET':

			case MYSQLI_TYPE_TINY_BLOB :
//			case MYSQLI_TYPE_CHAR :
			case MYSQLI_TYPE_STRING :
			case MYSQLI_TYPE_ENUM :
			case MYSQLI_TYPE_SET :
			case 253 :
				if ($len <= $this->blobSize) {
					return 'C';
				}

			case 'TEXT':
			case 'LONGTEXT':
			case 'MEDIUMTEXT':
				return 'X';

			// php_mysql extension always returns 'blob' even if 'text'
			// so we have to check whether binary...
			case 'IMAGE':
			case 'LONGBLOB':
			case 'BLOB':
			case 'MEDIUMBLOB':

			case MYSQLI_TYPE_BLOB :
			case MYSQLI_TYPE_LONG_BLOB :
			case MYSQLI_TYPE_MEDIUM_BLOB :
				return !empty($fieldobj->binary) ? 'B' : 'X';

			case 'YEAR':
			case 'DATE':
			case MYSQLI_TYPE_DATE :
			case MYSQLI_TYPE_YEAR :
				return 'D';

			case 'TIME':
			case 'DATETIME':
			case 'TIMESTAMP':

			case MYSQLI_TYPE_DATETIME :
			case MYSQLI_TYPE_NEWDATE :
			case MYSQLI_TYPE_TIME :
			case MYSQLI_TYPE_TIMESTAMP :
				return 'T';

			case 'INT':
			case 'INTEGER':
			case 'BIGINT':
			case 'TINYINT':
			case 'MEDIUMINT':
			case 'SMALLINT':

			case MYSQLI_TYPE_INT24 :
			case MYSQLI_TYPE_LONG :
			case MYSQLI_TYPE_LONGLONG :
			case MYSQLI_TYPE_SHORT :
			case MYSQLI_TYPE_TINY :
				if (!empty($fieldobj->primary_key)) {
					return 'R';
				}
				return 'I';

			// Added floating-point types
			// Maybe not necessary.
			case 'FLOAT':
			case 'DOUBLE':
//			case 'DOUBLE PRECISION':
			case 'DECIMAL':
			case 'DEC':
			case 'FIXED':
			default:
				//if (!is_numeric($t)) echo "<p>--- Error in type matching $t -----</p>";
				return 'N';
		}
	}


} // rs class

/**
 * Class ADORecordSet_array_mysqli
 */
class ADORecordSet_array_mysqli extends ADORecordSet_array
{
	/**
	 * Get the MetaType character for a given field type.
	 *
	 * @param string|object $t The type to get the MetaType character for.
	 * @param int $len (Optional) Redundant. Will always be set to -1.
	 * @param bool|object $fieldobj (Optional)
	 *
	 * @return string The MetaType
	 */
	function MetaType($t, $len = -1, $fieldobj = false)
	{
		if (is_object($t)) {
			$fieldobj = $t;
			$t = $fieldobj->type;
			$len = $fieldobj->max_length;
		}

		$len = -1; // mysql max_length is not accurate
		switch (strtoupper($t)) {
			case 'STRING':
			case 'CHAR':
			case 'VARCHAR':
			case 'TINYBLOB':
			case 'TINYTEXT':
			case 'ENUM':
			case 'SET':

			case MYSQLI_TYPE_TINY_BLOB :
//			case MYSQLI_TYPE_CHAR :
			case MYSQLI_TYPE_STRING :
			case MYSQLI_TYPE_ENUM :
			case MYSQLI_TYPE_SET :
			case 253 :
				if ($len <= $this->blobSize) {
					return 'C';
				}

			case 'TEXT':
			case 'LONGTEXT':
			case 'MEDIUMTEXT':
				return 'X';

			// php_mysql extension always returns 'blob' even if 'text'
			// so we have to check whether binary...
			case 'IMAGE':
			case 'LONGBLOB':
			case 'BLOB':
			case 'MEDIUMBLOB':

			case MYSQLI_TYPE_BLOB :
			case MYSQLI_TYPE_LONG_BLOB :
			case MYSQLI_TYPE_MEDIUM_BLOB :
				return !empty($fieldobj->binary) ? 'B' : 'X';

			case 'YEAR':
			case 'DATE':
			case MYSQLI_TYPE_DATE :
			case MYSQLI_TYPE_YEAR :
				return 'D';

			case 'TIME':
			case 'DATETIME':
			case 'TIMESTAMP':

			case MYSQLI_TYPE_DATETIME :
			case MYSQLI_TYPE_NEWDATE :
			case MYSQLI_TYPE_TIME :
			case MYSQLI_TYPE_TIMESTAMP :
				return 'T';

			case 'INT':
			case 'INTEGER':
			case 'BIGINT':
			case 'TINYINT':
			case 'MEDIUMINT':
			case 'SMALLINT':

			case MYSQLI_TYPE_INT24 :
			case MYSQLI_TYPE_LONG :
			case MYSQLI_TYPE_LONGLONG :
			case MYSQLI_TYPE_SHORT :
			case MYSQLI_TYPE_TINY :
				if (!empty($fieldobj->primary_key)) {
					return 'R';
				}
				return 'I';

			// Added floating-point types
			// Maybe not necessary.
			case 'FLOAT':
			case 'DOUBLE':
//			case 'DOUBLE PRECISION':
			case 'DECIMAL':
			case 'DEC':
			case 'FIXED':
			default:
				//if (!is_numeric($t)) echo "<p>--- Error in type matching $t -----</p>";
				return 'N';
		}
	}
}

} // if defined _ADODB_MYSQLI_LAYER