2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/29/2004 *
4 * =============== Last change: 08/29/2004 *
6 * -------------------------------------------------------------------- *
7 * File : lib-mysql3.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Database layer for MySQL +3.x server *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Datenbankschicht fuer MySQL +3.x Server *
12 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
23 * This program is distributed in the hope that it will be useful, *
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
26 * GNU General Public License for more details. *
28 * You should have received a copy of the GNU General Public License *
29 * along with this program; if not, write to the Free Software *
30 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
41 function SQL_QUERY ($sql_string, $F, $L) {
42 global $link, $CSS, $OK;
45 if (!is_resource($link)) return false;
47 // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
48 $sql_string = str_replace("\t", " ", str_replace("\n", " ", str_replace("\r", " ", $sql_string)));
50 // Replace {!_MYSQL_PREFIX!} with constant, closes #84. Thanks to profi-concept
51 $sql_string = str_replace("{!_MYSQL_PREFIX!}", constant('_MYSQL_PREFIX'), $sql_string);
54 $querytimeBefore = array_sum(explode(' ', microtime()));
57 //* DEBUG: */ echo $sql_string."<br />\n";
58 $result = mysql_query($sql_string, $link)
59 or addFatalMessage($F." (".$L."):".mysql_error()."<br />
64 $querytimeAfter = array_sum(explode(' ', microtime()));
66 // Calculate query time
67 $queryTime = $querytimeAfter - $querytimeBefore;
69 // Save last successfull query
70 setConfigEntry('db_last_query', $sql_string);
73 incrementConfigEntry('sql_count');
76 //* DEBUG: */ print "Query=<pre>".$sql_string."</pre>, affected=<strong>".SQL_AFFECTEDROWS()."</strong>, numrows=<strong>".SQL_NUMROWS($result)."</strong><br />\n";
78 if (($CSS != "1") && ($CSS != "-1") && (isBooleanConstantAndTrue('DEBUG_MODE')) && (isBooleanConstantAndTrue('DEBUG_SQL'))) {
82 $fp = fopen(constant('PATH')."inc/cache/mysql.log", 'a') or mxchange_die("Cannot write mysql.log!");
85 fwrite($fp, "Module=".$GLOBALS['module']."\n");
88 fwrite($fp, $F."(LINE=".$L."|NUM=".SQL_NUMROWS($result)."|AFFECTED=".SQL_AFFECTEDROWS()."|QUERYTIME:".$queryTime."): ".str_replace('\r', "", str_replace('\n', " ", $sql_string))."\n");
93 if (!isConfigEntrySet('db_hits_run')) {
94 // Count in dummy variable
95 setConfigEntry('db_hits_run', 1);
97 // Count to config array
98 incrementConfigEntry('db_hits_run');
106 function SQL_NUMROWS ($result) {
107 // Is the result a valid resource?
108 if (is_resource($result)) {
109 // Get the count of rows from database
110 $lines = mysql_num_rows($result);
112 // Is the result empty? Then we have an error!
113 if (empty($lines)) $lines = 0;
115 // No resource given, no lines found!
122 function SQL_AFFECTEDROWS() {
125 // Valid link resource?
126 if (!is_resource($link)) return false;
129 $lines = mysql_affected_rows($link);
136 function SQL_FETCHROW($result) {
140 // Is a result resource set?
141 if (!is_resource($result)) return false;
143 $DATA = mysql_fetch_row($result);
148 function SQL_FETCHARRAY($res, $nr=0, $remove_numerical=true) {
149 // Is a result resource set?
150 if (!is_resource($res)) return false;
155 // Load row from database
156 $row = mysql_fetch_array($res);
158 // Return only arrays here
159 if (is_array($row)) {
160 // Shall we remove numerical data here automatically?
161 if ($remove_numerical) {
162 // So let's remove all numerical elements to save memory!
164 for ($idx = 0; $idx < ($max / 2); $idx++) {
173 // Return a false here...
179 function SQL_RESULT ($res, $row, $field) {
180 $result = mysql_result($res, $row, $field);
185 function SQL_CONNECT ($host, $login, $password, $F, $L) {
186 $connect = mysql_connect($host, $login, $password) or addFatalMessage($F." (".$L."):".mysql_error());
190 // SQL select database
191 function SQL_SELECT_DB ($dbName, $link, $F, $L) {
192 // Is there still a valid link? If not, skip it.
193 if (!is_resource($link)) return false;
195 return mysql_select_db($dbName, $link) or addFatalMessage($F." (".$L."):".mysql_error());
199 function SQL_CLOSE (&$link, $F, $L) {
200 global $cacheInstance, $cacheArray;
202 if (!is_resource($link)) {
207 // Do we need to update cache/db counter?
208 //* DEBUG: */ echo "DB=".getConfig('db_hits').",CACHE=".getConfig('cache_hits')."<br />\n";
209 if ((GET_EXT_VERSION("cache") >= "0.0.7") && (getConfig('db_hits') > 0) && (getConfig('cache_hits') > 0) && (is_object($cacheInstance))) {
211 incrementConfigEntry('db_hits', getConfig('db_hits_run'));
213 // Update counter for db/cache
214 UPDATE_CONFIG(array("db_hits", "cache_hits"), array(bigintval(getConfig('db_hits')), bigintval(getConfig('cache_hits'))));
217 // Close database link and forget the link
218 $close = mysql_close($link) or addFatalMessage($F." (".$L."):".mysql_error());
224 function SQL_FREERESULT ($result) {
225 if (!is_resource($result)) {
230 $res = mysql_free_result($result);
234 // SQL string escaping
235 function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true) {
239 if (!is_resource($link)) return false;
250 $eval = "\$query = sprintf(\"".$qstring."\"";
251 foreach ($data as $var) {
252 if ((!empty($var)) || ($var === 0)) {
253 $eval .= ", SQL_ESCAPE(\"".$var."\",true,".$strip.")";
262 //* DEBUG: */ $fp = fopen(constant('PATH')."inc/cache/escape_debug.log", 'a') or mxchange_die("Cannot write debug.log!");
263 //* DEBUG: */ fwrite($fp, $F."(".$L."): ".str_replace("\r", "", str_replace("\n", " ", $eval))."\n");
264 //* DEBUG: */ fclose($fp);
269 // Was the eval() command fine?
270 if ($query == "failed") {
271 // Something went wrong?
272 debug_report_bug("eval={$eval}");
276 // Run SQL query (default)
277 return SQL_QUERY($query, $F, $L);
279 // Return secured string
284 // Get ID from last INSERT command
285 function SQL_INSERTID () {
287 if (!is_resource($link)) return false;
288 return mysql_insert_id();
291 // Escape a string for the database
292 function SQL_ESCAPE ($str, $secureString=true,$strip=true) {
295 // Secure string first? (which is the default behaviour!)
298 $str = secureString($str, $strip);
301 if (!is_resource($link)) {
302 // Fall-back to smartAddSlashes() when there is no link
303 return smartAddSlashes($str);
304 } elseif (function_exists('mysql_real_escape_string')) {
305 // The new and improved version
306 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):str={$str}<br />\n";
307 return mysql_real_escape_string($str, $link);
308 } elseif (function_exists('mysql_escape_string')) {
309 // The obsolete function
310 return mysql_escape_string($str, $link);
312 // If nothing else works, fall back to smartAddSlashes()
313 return smartAddSlashes($str);
317 // SELECT query string from table, columns and so on... ;-)
318 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
319 // Is columns an array?
320 if (!is_array($columns)) {
322 trigger_error(sprintf("columns is not array. %s!=array", gettype($columns)));
325 // Prepare the SQL statement
326 $SQL = "SELECT `".implode("`, `", $columns)."` FROM `{!_MYSQL_PREFIX!}_%s` WHERE ``='%s' LIMIT 1";
329 return SQL_QUERY_ESC($SQL,
337 // ALTER TABLE wrapper function
338 function SQL_ALTER_TABLE ($sql, $F, $L) {
339 // This is the default result...
342 // Determine index/fulltext/unique word
343 // 12 3 3 2 2 3 3 2 2 3 3 21
344 $noIndex = ((eregi("INDEX", $sql) == false) && (eregi("FULLTEXT", $sql) == false) && (eregi("UNIQUE", $sql) == false));
346 // Shall we add/drop?
347 if (((eregi("ADD", $sql) > 0) || (eregi("DROP", $sql) > 0)) && ($noIndex)) {
348 // Extract table name
349 $tableArray = explode(" ", $sql);
350 $tableName = str_replace("`", "", $tableArray[2]);
352 // And column name as well
353 $columnName = str_replace("`", "", $tableArray[4]);
355 // Get column information
356 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM %s LIKE '%s'",
357 array($tableName, $columnName), $F, $L);
359 // Do we have no entry on ADD or an entry on DROP?
360 // 123 4 4 3 3 4 4 32 23 4 4 3 3 4 4 321
361 if (((SQL_NUMROWS($result) == 0) && (eregi("ADD", $sql) > 0)) || ((SQL_NUMROWS($result) == 1) && (eregi("DROP", $sql) > 0))) {
363 $result = SQL_QUERY($sql, $F, $L, false);
366 // Send it to the SQL_QUERY() function
367 $result = SQL_QUERY($sql, $F, $L, false);