30require_once DOL_DOCUMENT_ROOT.
'/core/db/DoliDB.class.php';
43 const LABEL =
'MySQL or MariaDB';
66 if (!empty($conf->db->character_set)) {
67 $this->forcecharset = $conf->db->character_set;
69 if (!empty($conf->db->dolibarr_main_db_collation)) {
70 $this->forcecollate = $conf->db->dolibarr_main_db_collation;
73 $this->database_user = $user;
74 $this->database_host = $host;
75 $this->database_port = $port;
77 $this->transaction_opened = 0;
81 if (!class_exists(
'mysqli')) {
82 $this->connected =
false;
84 $this->
error =
"Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.";
85 dol_syslog(get_class($this).
"::DoliDBMysqli : Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.", LOG_ERR);
89 $this->connected =
false;
91 $this->
error = $langs->trans(
"ErrorWrongHostParameter");
92 dol_syslog(get_class($this).
"::DoliDBMysqli : Connect error, wrong host parameters", LOG_ERR);
97 $this->db = $this->
connect($host, $user, $pass,
'', $port);
99 if ($this->db && empty($this->db->connect_errno)) {
100 $this->connected =
true;
103 $this->connected =
false;
105 $this->
error = empty($this->db) ?
'Failed to connect' : $this->db->connect_error;
106 dol_syslog(get_class($this).
"::DoliDBMysqli Connect error: ".$this->
error, LOG_ERR);
109 $disableforcecharset = 0;
112 if ($this->connected && $name) {
114 $this->database_selected =
true;
115 $this->database_name = $name;
119 $clientmustbe = empty($conf->db->character_set) ?
'utf8' : (string) $conf->db->character_set;
120 if (preg_match(
'/latin1/', $clientmustbe)) {
121 $clientmustbe =
'utf8';
124 if (empty($disableforcecharset) && $this->db->character_set_name() != $clientmustbe) {
126 dol_syslog(get_class($this).
"::DoliDBMysqli You should set the \$dolibarr_main_db_character_set and \$dolibarr_main_db_collation for the PHP to the same as the database default, so to ".$this->db->character_set_name().
" or upgrade database default to ".$clientmustbe.
".", LOG_WARNING);
133 $this->db->set_charset($clientmustbe);
135 print
'Failed to force character_set_client to '.$clientmustbe.
" (according to setup) to match the one of the server database.<br>\n";
136 print $e->getMessage();
138 if ($clientmustbe !=
'utf8') {
139 print
'Edit conf/conf.php file to set a charset "utf8"';
140 if ($clientmustbe !=
'utf8mb4') {
141 print
' or "utf8mb4"';
143 print
' instead of "'.$clientmustbe.
'".'.
"\n";
148 $collation = (empty($conf) ?
'utf8_unicode_ci' : $conf->db->dolibarr_main_db_collation);
149 if (preg_match(
'/latin1/', $collation)) {
150 $collation =
'utf8_unicode_ci';
153 if (!preg_match(
'/general/', $collation)) {
154 $this->db->query(
"SET collation_connection = ".$collation);
158 $this->database_selected =
false;
159 $this->database_name =
'';
162 dol_syslog(get_class($this).
"::DoliDBMysqli : Select_db error ".$this->
error, LOG_ERR);
166 $this->database_selected =
false;
168 if ($this->connected) {
170 $clientmustbe = empty($conf->db->character_set) ?
'utf8' : (string) $conf->db->character_set;
171 if (preg_match(
'/latin1/', $clientmustbe)) {
172 $clientmustbe =
'utf8';
174 if (preg_match(
'/utf8mb4/', $clientmustbe)) {
175 $clientmustbe =
'utf8';
178 if (empty($disableforcecharset) && $this->db->character_set_name() != $clientmustbe) {
179 $this->db->set_charset($clientmustbe);
181 $collation = $conf->db->dolibarr_main_db_collation;
182 if (preg_match(
'/latin1/', $collation)) {
183 $collation =
'utf8_unicode_ci';
185 if (preg_match(
'/utf8mb4/', $collation)) {
186 $collation =
'utf8_unicode_ci';
189 if (!preg_match(
'/general/', $collation)) {
190 $this->db->query(
"SET collation_connection = ".$collation);
206 return " FORCE INDEX(".preg_replace(
'/[^a-z0-9_]/',
'', $nameofindex).
")";
233 dol_syslog(get_class($this).
"::select_db database=".$database, LOG_DEBUG);
236 $result = $this->db->select_db($database);
255 public function connect($host, $login, $passwd, $name, $port = 0)
257 dol_syslog(get_class($this).
"::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name", LOG_DEBUG);
263 if (!class_exists(
'mysqli')) {
267 if (strpos($host,
'ssl://') === 0) {
268 $tmp =
new mysqliDoli($host, $login, $passwd, $name, $port);
270 $tmp =
new mysqli($host, $login, $passwd, $name, $port);
273 dol_syslog(get_class($this).
"::connect failed", LOG_DEBUG);
285 return $this->db->server_info;
295 return $this->db->client_info;
308 if ($this->transaction_opened > 0) {
309 dol_syslog(get_class($this).
"::close Closing a connection with an opened transaction depth=".$this->transaction_opened, LOG_ERR);
311 $this->connected =
false;
312 return $this->db->close();
329 public function query($query, $usesavepoint = 0,
$type =
'auto', $result_mode = 0)
331 global $dolibarr_main_db_readonly;
333 $query = trim($query);
335 if (!in_array($query, array(
'BEGIN',
'COMMIT',
'ROLLBACK'))) {
336 $SYSLOG_SQL_LIMIT = 10000;
337 dol_syslog(
'sql='.substr($query, 0, $SYSLOG_SQL_LIMIT), LOG_DEBUG);
343 if (!empty($dolibarr_main_db_readonly)) {
344 if (preg_match(
'/^(INSERT|UPDATE|REPLACE|DELETE|CREATE|ALTER|TRUNCATE|DROP)/i', $query)) {
345 $this->
lasterror =
'Application in read-only mode';
353 $ret = $this->db->query($query, $result_mode);
355 dol_syslog(get_class($this).
"::query Exception in query instead of returning an error: ".$e->getMessage(), LOG_ERR);
359 if (!preg_match(
"/^COMMIT/i", $query) && !preg_match(
"/^ROLLBACK/i", $query)) {
367 dol_syslog(get_class($this).
"::query SQL Error query: ".$query, LOG_ERR);
369 dol_syslog(get_class($this).
"::query SQL Error message: ".$this->
lasterrno.
" ".$this->lasterror.self::getCallerInfoString(), LOG_ERR);
373 $this->_results = $ret;
386 $backtrace = debug_backtrace();
388 if (count($backtrace) >= 1) {
389 $trace = $backtrace[1];
390 if (isset($trace[
'file'], $trace[
'line'])) {
391 $msg =
" From {$trace['file']}:{$trace['line']}.";
408 if (!is_object($resultset)) {
409 $resultset = $this->_results;
411 return $resultset->fetch_object();
426 if (!is_object($resultset)) {
427 $resultset = $this->_results;
429 return $resultset->fetch_array();
443 if (!is_bool($resultset)) {
444 if (!is_object($resultset)) {
445 $resultset = $this->_results;
447 return $resultset->fetch_row();
466 if (!is_object($resultset)) {
467 $resultset = $this->_results;
469 return isset($resultset->num_rows) ? $resultset->num_rows : 0;
484 if (!is_object($resultset)) {
485 $resultset = $this->_results;
489 return $this->db->affected_rows;
498 public function free($resultset =
null)
501 if (!is_object($resultset)) {
502 $resultset = $this->_results;
505 if (is_object($resultset)) {
506 $resultset->free_result();
518 return $this->db->real_escape_string((
string) $stringtoencode);
530 return str_replace(array(
'\\',
'_',
'%'), array(
'\\\\',
'\_',
'\%'), (
string) $stringtoencode);
540 if (!$this->connected) {
542 return 'DB_ERROR_FAILED_TO_CONNECT';
545 $errorcode_map = array(
546 1004 =>
'DB_ERROR_CANNOT_CREATE',
547 1005 =>
'DB_ERROR_CANNOT_CREATE',
548 1006 =>
'DB_ERROR_CANNOT_CREATE',
549 1007 =>
'DB_ERROR_ALREADY_EXISTS',
550 1008 =>
'DB_ERROR_CANNOT_DROP',
551 1022 =>
'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
552 1025 =>
'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
553 1044 =>
'DB_ERROR_ACCESSDENIED',
554 1046 =>
'DB_ERROR_NODBSELECTED',
555 1048 =>
'DB_ERROR_CONSTRAINT',
556 1050 =>
'DB_ERROR_TABLE_ALREADY_EXISTS',
557 1051 =>
'DB_ERROR_NOSUCHTABLE',
558 1054 =>
'DB_ERROR_NOSUCHFIELD',
559 1060 =>
'DB_ERROR_COLUMN_ALREADY_EXISTS',
560 1061 =>
'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
561 1062 =>
'DB_ERROR_RECORD_ALREADY_EXISTS',
562 1064 =>
'DB_ERROR_SYNTAX',
563 1068 =>
'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
564 1075 =>
'DB_ERROR_CANT_DROP_PRIMARY_KEY',
565 1091 =>
'DB_ERROR_NOSUCHFIELD',
566 1100 =>
'DB_ERROR_NOT_LOCKED',
567 1136 =>
'DB_ERROR_VALUE_COUNT_ON_ROW',
568 1146 =>
'DB_ERROR_NOSUCHTABLE',
569 1215 =>
'DB_ERROR_CANNOT_ADD_FOREIGN_KEY_CONSTRAINT',
570 1216 =>
'DB_ERROR_NO_PARENT',
571 1217 =>
'DB_ERROR_CHILD_EXISTS',
572 1396 =>
'DB_ERROR_USER_ALREADY_EXISTS',
573 1451 =>
'DB_ERROR_CHILD_EXISTS',
574 1826 =>
'DB_ERROR_KEY_NAME_ALREADY_EXISTS'
577 if (isset($errorcode_map[$this->db->errno])) {
578 return $errorcode_map[$this->db->errno];
580 $errno = $this->db->errno;
581 return ($errno ?
'DB_ERROR_'.$errno :
'0');
592 if (!$this->connected) {
594 return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
596 return $this->db->error;
611 return $this->db->insert_id;
622 public function encrypt($fieldorvalue, $withQuotes = 1)
627 $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
630 $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey :
'');
632 $escapedstringwithquotes = ($withQuotes ?
"'" :
"").$this->
escape($fieldorvalue).($withQuotes ?
"'" :
"");
634 if ($cryptType && !empty($cryptKey)) {
635 if ($cryptType == 2) {
636 $escapedstringwithquotes =
"AES_ENCRYPT(".$escapedstringwithquotes.
", '".$this->
escape($cryptKey).
"')";
637 } elseif ($cryptType == 1) {
638 $escapedstringwithquotes =
"DES_ENCRYPT(".$escapedstringwithquotes.
", '".$this->
escape($cryptKey).
"')";
642 return $escapedstringwithquotes;
656 $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
659 $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey :
'');
663 if ($cryptType && !empty($cryptKey)) {
664 if ($cryptType == 2) {
665 $return =
'AES_DECRYPT('.$value.
',\''.$cryptKey.
'\')
';
666 } elseif ($cryptType == 1) {
667 $return = 'DES_DECRYPT(
'.$value.',\
''.$cryptKey.
'\')
';
675 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
681 public function DDLGetConnectId()
684 $resql = $this->query('SELECT CONNECTION_ID()
');
686 $row = $this->fetch_row($resql);
693 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
705 public function DDLCreateDb($database, $charset = '
', $collation = '', $owner = '')
708 if (empty($charset)) {
709 $charset = $this->forcecharset;
711 if (empty($collation)) {
712 $collation = $this->forcecollate;
715 // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
716 $sql = "CREATE DATABASE `".$this->escape($database)."`";
717 $sql .= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
719 dol_syslog($sql, LOG_DEBUG);
720 $ret = $this->query($sql);
722 // We try again for compatibility with Mysql < 4.1.1
723 $sql = "CREATE DATABASE `".$this->escape($database)."`";
724 dol_syslog($sql, LOG_DEBUG);
725 $ret = $this->query($sql);
731 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
739 public function DDLListTables($database, $table = '
')
742 $listtables = array();
746 $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i
', '', $table);
748 $like = "LIKE '".$this->escape($tmptable)."'";
750 $tmpdatabase = preg_replace('/[^a-z0-9\.\-\_]/i
', '', $database);
752 $sql = "SHOW TABLES FROM `".$tmpdatabase."` ".$like.";";
754 $result = $this->query($sql);
756 while ($row = $this->fetch_row($result)) {
757 $listtables[] = $row[0];
763 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
771 public function DDLListTablesFull($database, $table = '
')
774 $listtables = array();
778 $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i
', '', $table);
780 $like = "LIKE '".$this->escape($tmptable)."'";
782 $tmpdatabase = preg_replace('/[^a-z0-9\.\-\_]/i
', '', $database);
784 $sql = "SHOW FULL TABLES FROM `".$tmpdatabase."` ".$like.";";
786 $result = $this->query($sql);
788 while ($row = $this->fetch_row($result)) {
789 $listtables[] = $row;
795 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
802 public function DDLInfoTable($table)
805 $infotables = array();
807 $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i
', '', $table);
809 $sql = "SHOW FULL COLUMNS FROM ".$tmptable.";";
811 dol_syslog($sql, LOG_DEBUG);
812 $result = $this->query($sql);
814 while ($row = $this->fetch_row($result)) {
815 $infotables[] = $row;
821 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
834 public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
837 // @TODO: $fulltext_keys parameter is unused
847 // Keys found into the array $fields: type,value,attribute,null,default,extra
848 // ex. : $fields['rowid
'] = array(
849 // 'type'=>'int' or 'integer
',
851 // 'null'=>'not
null',
852 // 'extra
'=> 'auto_increment
'
854 $sql = "CREATE TABLE ".$this->sanitize($table)."(";
856 $sqlfields = array();
857 foreach ($fields as $field_name => $field_desc) {
858 $sqlfields[$i] = $this->sanitize($field_name)." ";
859 $sqlfields[$i] .= $this->sanitize($field_desc['type']);
860 if (isset($field_desc['value
']) && $field_desc['value
'] !== '') {
861 $sqlfields[$i] .= "(".$this->sanitize($field_desc['value
']).")";
863 if (isset($field_desc['attribute
']) && $field_desc['attribute
'] !== '') {
864 $sqlfields[$i] .= " ".$this->sanitize($field_desc['attribute
'], 0, 0, 1); // Allow space to accept attributes like "ON UPDATE CURRENT_TIMESTAMP"
866 if (isset($field_desc['default']) && $field_desc['default'] !== '') {
867 if (in_array($field_desc['type'], array('tinyint
', 'smallint
', 'int', 'double'))) {
868 $sqlfields[$i] .= " DEFAULT ".((float) $field_desc['default']);
869 } elseif ($field_desc['default'] == 'null' || $field_desc['default'] == 'CURRENT_TIMESTAMP
') {
870 $sqlfields[$i] .= " DEFAULT ".$this->sanitize($field_desc['default']);
872 $sqlfields[$i] .= " DEFAULT '".$this->escape($field_desc['default'])."'";
875 if (isset($field_desc['null']) && $field_desc['null'] !== '') {
876 $sqlfields[$i] .= " ".$this->sanitize($field_desc['null'], 0, 0, 1);
878 if (isset($field_desc['extra
']) && $field_desc['extra
'] !== '') {
879 $sqlfields[$i] .= " ".$this->sanitize($field_desc['extra
'], 0, 0, 1);
881 if (!empty($primary_key) && $primary_key == $field_name) {
882 $sqlfields[$i] .= " AUTO_INCREMENT PRIMARY KEY"; // mysql instruction that will be converted by driver late
887 if (is_array($unique_keys)) {
889 foreach ($unique_keys as $key => $value) {
890 $sqluq[$i] = "UNIQUE KEY '".$this->sanitize($key)."' ('".$this->escape($value)."')";
894 if (is_array($keys)) {
896 foreach ($keys as $key => $value) {
897 $sqlk[$i] = "KEY ".$this->sanitize($key)." (".$value.")";
901 $sql .= implode(',
', $sqlfields);
902 if (!is_array($unique_keys) && $unique_keys != "") {
903 $sql .= ",".implode(',
', $sqluq);
905 if (is_array($keys)) {
906 $sql .= ",".implode(',
', $sqlk);
909 $sql .= " engine=".$this->sanitize($type);
911 if (!$this->query($sql)) {
918 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
925 public function DDLDropTable($table)
928 $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i
', '', $table);
930 $sql = "DROP TABLE ".$this->sanitize($tmptable);
932 if (!$this->query($sql)) {
939 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
947 public function DDLDescTable($table, $field = "")
950 $sql = "DESC ".$this->sanitize($table)." ".$this->sanitize($field);
952 dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
953 $this->_results = $this->query($sql);
954 return $this->_results;
957 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
967 public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
970 // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
971 // ex. : $field_desc = array('
type'=>'int','value
'=>'11
','null'=>'not
null','extra
'=> 'auto_increment
');
972 $sql = "ALTER TABLE ".$this->sanitize($table)." ADD ".$this->sanitize($field_name)." ";
973 $sql .= $this->sanitize($field_desc['type']);
974 if (isset($field_desc['value
']) && preg_match("/^[^\s]/i", $field_desc['value
'])) {
975 if (!in_array($field_desc['type'], array('tinyint
', 'smallint
', 'int', 'date
', 'datetime
')) && $field_desc['value
']) {
976 $sql .= "(".$this->sanitize($field_desc['value
']).")";
979 if (isset($field_desc['attribute
']) && preg_match("/^[^\s]/i", $field_desc['attribute
'])) {
980 $sql .= " ".$this->sanitize($field_desc['attribute
']);
982 if (isset($field_desc['null']) && preg_match("/^[^\s]/i", $field_desc['null'])) {
983 $sql .= " ".$this->sanitize($field_desc['null']);
985 if (isset($field_desc['default']) && preg_match("/^[^\s]/i", $field_desc['default'])) {
986 if (in_array($field_desc['type'], array('tinyint
', 'smallint
', 'int', 'double'))) {
987 $sql .= " DEFAULT ".((float) $field_desc['default']);
988 } elseif ($field_desc['default'] == 'null' || $field_desc['default'] == 'CURRENT_TIMESTAMP
') {
989 $sql .= " DEFAULT ".$this->sanitize($field_desc['default']);
991 $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'";
994 if (isset($field_desc['extra
']) && preg_match("/^[^\s]/i", $field_desc['extra
'])) {
995 $sql .= " ".$this->sanitize($field_desc['extra
'], 0, 0, 1);
997 $sql .= " ".$this->sanitize($field_position, 0, 0, 1);
999 dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
1000 if ($this->query($sql)) {
1006 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1015 public function DDLUpdateField($table, $field_name, $field_desc)
1018 $sql = "ALTER TABLE ".$this->sanitize($table);
1019 $sql .= " MODIFY COLUMN ".$this->sanitize($field_name)." ".$this->sanitize($field_desc['
type']);
1020 if (in_array($field_desc['type'], array('double', 'tinyint
', 'int', 'varchar
')) && array_key_exists('value
', $field_desc) && $field_desc['value
']) {
1021 $sql .= "(".$this->sanitize($field_desc['value
']).")";
1023 if (isset($field_desc['null']) && ($field_desc['null'] == 'not
null' || $field_desc['null'] == 'NOT NULL
')) {
1024 // We will try to change format of column to NOT NULL. To be sure the ALTER works, we try to update fields that are NULL
1025 if ($field_desc['type'] == 'varchar
' || $field_desc['type'] == 'text
') {
1026 $sqlbis = "UPDATE ".$this->sanitize($table)." SET ".$this->sanitize($field_name)." = '".$this->escape(isset($field_desc['default']) ? $field_desc['default'] : '')."' WHERE ".$this->sanitize($field_name)." IS NULL";
1027 $this->query($sqlbis);
1028 } elseif (in_array($field_desc['type'], array('tinyint
', 'smallint
', 'int', 'double'))) {
1029 $sqlbis = "UPDATE ".$this->sanitize($table)." SET ".$this->sanitize($field_name)." = ".((float) $this->escape(isset($field_desc['default']) ? $field_desc['default'] : 0))." WHERE ".$this->sanitize($field_name)." IS NULL";
1030 $this->query($sqlbis);
1033 $sql .= " NOT NULL";
1036 if (isset($field_desc['default']) && $field_desc['default'] != '') {
1037 if (in_array($field_desc['type'], array('tinyint
', 'smallint
', 'int', 'double'))) {
1038 $sql .= " DEFAULT ".((float) $field_desc['default']);
1039 } elseif ($field_desc['type'] != 'text
') {
1040 $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
1044 dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
1045 if (!$this->query($sql)) {
1052 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1060 public function DDLDropField($table, $field_name)
1063 $tmp_field_name = preg_replace('/[^a-z0-9\.\-\_]/i
', '', $field_name);
1065 $sql = "ALTER TABLE ".$this->sanitize($table)." DROP COLUMN `".$this->sanitize($tmp_field_name)."`";
1066 if ($this->query($sql)) {
1069 $this->error = $this->lasterror();
1074 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1084 public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
1087 $sql = "CREATE USER '
".$this->escape($dolibarr_main_db_user)."' IDENTIFIED BY '".$this->escape($dolibarr_main_db_pass)."'";
1088 dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1089 $resql = $this->query($sql);
1091 if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS
') {
1094 // If user already exists, we continue to set permissions
1095 dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
1099 // Redo with localhost forced (sometimes user is created on %)
1100 $sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."'@'localhost
' IDENTIFIED BY '".$this->escape($dolibarr_main_db_pass)."'";
1101 $resql = $this->query($sql);
1103 $sql = "GRANT ALL PRIVILEGES ON ".$this->escape($dolibarr_main_db_name).".* TO '".$this->escape($dolibarr_main_db_user)."'@'".$this->escape($dolibarr_main_db_host)."'";
1104 dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
1105 $resql = $this->query($sql);
1107 $this->error = "Connected user not allowed to GRANT ALL PRIVILEGES ON ".$this->escape($dolibarr_main_db_name).".* TO '".$this->escape($dolibarr_main_db_user)."'@'".$this->escape($dolibarr_main_db_host)."'";
1111 $sql = "FLUSH Privileges";
1113 dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
1114 $resql = $this->query($sql);
1129 public function getDefaultCharacterSetDatabase()
1131 $resql = $this->query("SHOW VARIABLES LIKE 'character_set_database
'");
1133 // version Mysql < 4.1.1
1134 return $this->forcecharset;
1136 $liste = $this->fetch_array($resql);
1137 $tmpval = $liste['Value
'];
1147 public function getListOfCharacterSet()
1149 $resql = $this->query('SHOW CHARSET
');
1153 while ($obj = $this->fetch_object($resql)) {
1154 $liste[$i]['charset
'] = $obj->Charset;
1158 $this->free($resql);
1160 // version Mysql < 4.1.1
1172 public function getDefaultCollationDatabase()
1174 $resql = $this->query("SHOW VARIABLES LIKE 'collation_database
'");
1176 // version Mysql < 4.1.1
1177 return $this->forcecollate;
1179 $liste = $this->fetch_array($resql);
1180 $tmpval = $liste['Value
'];
1190 public function getListOfCollation()
1192 $resql = $this->query('SHOW COLLATION
');
1196 while ($obj = $this->fetch_object($resql)) {
1197 $liste[$i]['collation
'] = $obj->Collation;
1200 $this->free($resql);
1202 // version Mysql < 4.1.1
1213 public function getPathOfDump()
1215 $fullpathofdump = '/pathtomysqldump/mysqldump
';
1217 $resql = $this->query("SHOW VARIABLES LIKE 'basedir
'");
1219 $liste = $this->fetch_array($resql);
1220 $basedir = $liste['Value
'];
1221 $fullpathofdump = $basedir.(preg_match('/\/$/
', $basedir) ? '' : '/
').'bin/mysqldump
';
1223 return $fullpathofdump;
1231 public function getPathOfRestore()
1233 $fullpathofimport = '/pathtomysql/mysql
';
1235 $resql = $this->query("SHOW VARIABLES LIKE 'basedir
'");
1237 $liste = $this->fetch_array($resql);
1238 $basedir = $liste['Value
'];
1239 $fullpathofimport = $basedir.(preg_match('/\/$/
', $basedir) ? '' : '/
').'bin/mysql
';
1241 return $fullpathofimport;
1250 public function getServerParametersValues($filter = '
')
1254 $sql = 'SHOW VARIABLES
';
1256 $sql .= " LIKE '".$this->escape($filter)."'";
1258 $resql = $this->query($sql);
1260 while ($obj = $this->fetch_object($resql)) {
1261 $result[$obj->Variable_name] = $obj->Value;
1274 public function getServerStatusValues($filter = '
')
1278 $sql = 'SHOW STATUS
';
1280 $sql .= " LIKE '".$this->escape($filter)."'";
1282 $resql = $this->query($sql);
1284 while ($obj = $this->fetch_object($resql)) {
1285 $result[$obj->Variable_name] = $obj->Value;
1294if (class_exists('myslqi
')) {
1298 class mysqliDoli extends mysqli
1311 public function __construct($host, $user, $pass, $name, $port = 0, $socket = "")
1314 if (PHP_VERSION_ID >= 80100) {
1315 parent::__construct();
1317 // @phan-suppress-next-line PhanDeprecatedFunctionInternal
1320 if (strpos($host, 'ssl:
1321 $host = substr($host, 6);
1322 parent::options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT,
false);
1324 parent::ssl_set(
null,
null,
"",
null,
null);
1325 $flags = MYSQLI_CLIENT_SSL;
1327 parent::real_connect($host, $user, $pass, $name, $port, $socket, $flags);
Class to manage Dolibarr database access.
lastqueryerror()
Return last query in error.
lasterror()
Return last error label.
lasterrno()
Return last error code.
lastquery()
Return last request executed with query()
Class to manage Dolibarr database access for a MySQL database using the MySQLi extension.
fetch_array($resultset)
Return data as an array.
__construct($type, $host, $user, $pass, $name='', $port=0)
Constructor.
free($resultset=null)
Libere le dernier resultset utilise sur cette connection.
escapeforlike($stringtoencode)
Escape a string to insert data into a like.
num_rows($resultset)
Return number of lines for result of a SELECT.
const VERSIONMIN
Version min database.
error()
Return description of last error.
escape($stringtoencode)
Escape a string to insert data.
getVersion()
Return version of database server.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
encrypt($fieldorvalue, $withQuotes=1)
Encrypt sensitive data in database Warning: This function includes the escape and add the SQL simple ...
convertSQLFromMysql($line, $type='ddl')
Convert a SQL request in Mysql syntax to native syntax.
affected_rows($resultset)
Return the number of lines in the result of a request INSERT, DELETE or UPDATE.
select_db($database)
Select a database.
decrypt($value)
Decrypt sensitive data in database.
fetch_row($resultset)
Return data as an array.
last_insert_id($tab, $fieldid='rowid')
Get last ID after an insert INSERT.
const LABEL
Database label.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
hintindex($nameofindex)
Return SQL string to force an index.
connect($host, $login, $passwd, $name, $port=0)
Connect to server.
errno()
Return generic error code of last operation.
static getCallerInfoString()
Get caller info.
getDriverInfo()
Return version of database client driver.
close()
Close database connection.
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type