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, $_CONFIG, $OK;
44 // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
45 $sql_string = str_replace("\t", " ", str_replace("\n", " ", str_replace("\r", " ", $sql_string)));
48 $querytimeBefore = array_sum(explode(' ', microtime()));
51 //* DEBUG: */ echo $sql_string."<br />\n";
52 $result = @mysql_query($sql_string, $link)
53 or ADD_FATAL($F." (".$L."):".mysql_error()."<br />
54 ".MYSQL_QUERY_STRING."<br />
57 // Save last successfull query
58 $_CONFIG['db_last_query'] = $sql_string;
61 $querytimeAfter = array_sum(explode(' ', microtime()));
63 // Calculate query time
64 $queryTime = $querytimeAfter - $querytimeBefore;
67 if (!isset($_CONFIG['sql_count'])) $_CONFIG['sql_count'] = 0;
68 $_CONFIG['sql_count']++;
71 //* DEBUG: */ print "Query=<pre>".$sql_string."</pre>, affected=<b>".SQL_AFFECTEDROWS()."</b>, numrows=<b>".SQL_NUMROWS($result)."</b><br />\n";
73 if (($CSS != "1") && ($CSS != "-1") && (isBooleanConstantAndTrue('DEBUG_MODE')) && (isBooleanConstantAndTrue('DEBUG_SQL'))) {
77 $fp = @fopen(PATH."inc/cache/mysql.log", 'a') or mxchange_die("Cannot write mysql.log!");
80 fwrite($fp, "Module=".$GLOBALS['module']."\n");
83 fwrite($fp, $F."(LINE=".$L."|NUM=".SQL_NUMROWS($result)."|AFFECTED=".SQL_AFFECTEDROWS()."|QUERYTIME:".$queryTime."): ".str_replace('\r', "", str_replace('\n', " ", $sql_string))."\n");
88 if (!isset($_CONFIG['db_hits_run'])) {
89 // Count in dummy variable
90 $_CONFIG['db_hits_run'] = 1;
92 // Count to config array
93 $_CONFIG['db_hits_run']++;
101 function SQL_NUMROWS($result) {
102 // Is the result a valid resource?
103 if (is_resource($result)) {
104 // Get the count of rows from database
105 $lines = @mysql_num_rows($result);
107 // Is the result empty? Then we have an error!
108 if (empty($lines)) $lines = 0;
110 // No resource given, no lines found!
117 function SQL_AFFECTEDROWS() {
120 // Valid link resource?
121 if (!is_resource($link)) return false;
124 $lines = @mysql_affected_rows($link);
131 function SQL_FETCHROW($result) {
135 // Is a result resource set?
136 if (!is_resource($result)) return false;
138 $DATA = @mysql_fetch_row($result);
143 function SQL_FETCHARRAY($res, $nr=0, $remove_numerical=true) {
144 // Is a result resource set?
145 if (!is_resource($res)) return false;
150 // Load row from database
151 $row = @mysql_fetch_array($res);
153 // Return only arrays here
154 if (is_array($row)) {
155 // Shall we remove numerical data here automatically?
156 if ($remove_numerical) {
157 // So let's remove all numerical elements to save memory!
159 for ($idx = 0; $idx < ($max / 2); $idx++) {
168 // Return a false here...
174 function SQL_RESULT($res, $row, $field) {
175 $result = @mysql_result($res, $row, $field);
179 function SQL_CONNECT($host, $login, $password, $F, $L) {
180 $connect = @mysql_connect($host, $login, $password) or ADD_FATAL($F." (".$L."):".mysql_error());
183 // SQL select database
184 function SQL_SELECT_DB($dbName, $link, $F, $L) {
186 if (is_resource($link)) {
187 $select = @mysql_select_db($dbName, $link) or ADD_FATAL($F." (".$L."):".mysql_error());
192 function SQL_CLOSE(&$link, $F, $L) {
193 global $_CONFIG, $cacheInstance, $cacheArray;
195 // Is there still a valid link?
196 if (!is_resource($link)) {
200 //* DEBUG: */ echo "DB=".$_CONFIG['db_hits'].",CACHE=".$_CONFIG['cache_hits']."<br />\n";
201 if ((GET_EXT_VERSION("cache") >= "0.0.7") && (isset($_CONFIG['db_hits'])) && (isset($_CONFIG['cache_hits'])) && (is_object($cacheInstance))) {
203 $_CONFIG['db_hits'] += $_CONFIG['db_hits_run'];
205 // Update counter for db/cache
206 UPDATE_CONFIG(array("db_hits", "cache_hits"), array(bigintval($_CONFIG['db_hits']), bigintval($_CONFIG['cache_hits'])));
209 // Close database link and forget the link
210 $close = @mysql_close($link) or ADD_FATAL($F." (".$L."):".mysql_error());
215 function SQL_FREERESULT($result) {
216 if (!is_resource($result)) {
221 $res = @mysql_free_result($result);
224 // SQL string escaping
225 function SQL_QUERY_ESC($qstring, $data, $file, $line, $run=true, $strip=true) {
235 $eval = "\$query = sprintf(\"".$qstring."\"";
236 foreach ($data as $var) {
237 if ((!empty($var)) || ($var === 0)) {
238 $eval .= ", SQL_ESCAPE(\"".$var."\",true,".$strip.")";
247 //$fp = fopen(PATH."inc/cache/escape_debug.log", 'a') or mxchange_die("Cannot write debug.log!");
248 //fwrite($fp, $file."(".$line."): ".str_replace("\r", "", str_replace("\n", " ", $eval))."\n");
251 // Was the eval() command fine?
253 // Something went wrong?
254 print "eval=".htmlentities($eval)."<pre>";
255 debug_print_backtrace();
260 // Run SQL query (default)
261 return SQL_QUERY($query, $file, $line);
263 // Return secured string
267 // Get ID from last INSERT command
268 function SQL_INSERTID() {
269 return @mysql_insert_id();
271 // Escape a string for the database
272 function SQL_ESCAPE($str, $secureString=true,$strip=true) {
275 // Secure string first? (which is the default behaviour!)
278 $str = secureString($str, $strip);
281 if (!is_resource($link)) {
282 // Fall-back to addslashes() when there is no link
283 return addslashes($str);
286 if (function_exists('mysql_real_escape_string')) {
287 // The new and improved version
288 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):str={$str}<br />\n";
289 return mysql_real_escape_string($str, $link);
290 } elseif (function_exists('mysql_escape_string')) {
291 // The obsulete function
292 return mysql_escape_string($str, $link);
294 // If nothing else works
295 return addslashes($str);
298 // SELECT query string from table, columns and so on... ;-)
299 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
300 // Prepare the SQL statement
301 $SQL = "SELECT ".implode(", ", $columns)." FROM "._MYSQL_PREFIX."_".$table." WHERE ".$idRow."=%s LIMIT 1";
304 return SQL_QUERY_ESC($SQL, array(bigintval($id)), $F, $L);
306 // ALTER TABLE wrapper function
307 function SQL_ALTER_TABLE($sql, $F, $L) {
309 if (eregi("ADD", $sql) > 0) {
310 // Extract table name
311 $tableArray = explode(" ", $sql);
312 $tableName = str_replace("`", "", $tableArray[2]);
314 // And column name as well
315 $columnName = str_replace("`", "", $tableArray[4]);
317 // Get column information
318 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM %s LIKE '%s'",
319 array($tableName, $columnName), $F, $L);
321 // Do we have no entry?
322 if (SQL_NUMROWS($result) == 0) {
324 return SQL_QUERY($sql, $F, $L, false);
327 // Send it to the SQL_QUERY() function
328 return SQL_QUERY($sql, $F, $L, false);