Project

General

Profile

1 4 ryan
<?php
2 1362 Luisehahne
/**
3 1866 Luisehahne
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4 1362 Luisehahne
 *
5 1866 Luisehahne
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9 1362 Luisehahne
 *
10 1866 Luisehahne
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 1362 Luisehahne
 */
18 1866 Luisehahne
/**
19
 * WbDatabase.php
20
 *
21
 * @category     Core
22
 * @package      Core_database
23
 * @author       Werner v.d.Decken <wkl@isteam.de>
24
 * @author       Dietmar W. <dietmar.woellbrink@websitebaker.org>
25
 * @copyright    Werner v.d.Decken <wkl@isteam.de>
26
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
27
 * @version      0.0.9
28
 * @revision     $Revision$
29
 * @lastmodified $Date$
30
 * @deprecated   from WB version number 2.9
31
 * @description  Mysql database wrapper for use with websitebaker up to version 2.8.4
32
 */
33
34 1496 DarkViper
/* -------------------------------------------------------- */
35 1885 Luisehahne
@define('DATABASE_CLASS_LOADED', true);
36 4 ryan
37 1686 darkviper
class WbDatabase {
38 1763 Luisehahne
39 1686 darkviper
	private static $_oInstances = array();
40 1680 darkviper
41 1885 Luisehahne
	private $_db_handle  = null; // readonly from outside
42
	private $_db_name    = '';
43
	protected $sTablePrefix = '';
44 1889 Luisehahne
	protected $sCharset     = '';
45 1885 Luisehahne
	protected $connected    = false;
46
	protected $error        = '';
47
	protected $error_type   = '';
48
	protected $iQueryCount  = 0;
49 1362 Luisehahne
50 1683 darkviper
/* prevent from public instancing */
51 1686 darkviper
	protected function  __construct() {}
52 1683 darkviper
/* prevent from cloning */
53
	private function __clone() {}
54
/**
55 1686 darkviper
 * get a valid instance of this class
56
 * @param string $sIdentifier selector for several different instances
57
 * @return object
58
 */
59
	public static function getInstance($sIdentifier = 'core') {
60
		if( !isset(self::$_oInstances[$sIdentifier])) {
61
            $c = __CLASS__;
62
            self::$_oInstances[$sIdentifier] = new $c;
63
		}
64
		return self::$_oInstances[$sIdentifier];
65
	}
66
/**
67
 * disconnect and kills an existing instance
68
 * @param string $sIdentifier
69
 */
70
	public static function killInstance($sIdentifier) {
71
		if($sIdentifier != 'core') {
72
			if( isset(self::$_oInstances[$sIdentifier])) {
73
				self::$_oInstances[$sIdentifier]->disconnect();
74
				unset(self::$_oInstances[$sIdentifier]);
75
			}
76
		}
77
	}
78
/**
79 1683 darkviper
 * Connect to the database
80
 * @param string $url
81
 * @return bool
82
 *
83
 * Example for SQL-Url:  'mysql://user:password@demo.de[:3306]/datenbank'
84
 */
85
	public function doConnect($url = '') {
86 1885 Luisehahne
		$this->connected = false;
87 1680 darkviper
		if($url != '') {
88
			$aIni = parse_url($url);
89 1866 Luisehahne
90
			$scheme   = isset($aIni['scheme']) ? $aIni['scheme'] : 'mysql';
91
			$hostname = isset($aIni['host']) ? $aIni['host'] : '';
92
			$username = isset($aIni['user']) ? $aIni['user'] : '';
93
			$password = isset($aIni['pass']) ? $aIni['pass'] : '';
94
			$hostport = isset($aIni['port']) ? $aIni['port'] : '3306';
95
			$hostport = $hostport == '3306' ? '' : ':'.$hostport;
96
			$db_name  = ltrim(isset($aIni['path']) ? $aIni['path'] : '', '/\\');
97 1885 Luisehahne
			$sTmp = isset($aIni['query']) ? $aIni['query'] : '';
98
			$aQuery = explode('&', $sTmp);
99
			foreach($aQuery as $sArgument) {
100
				$aArg = explode('=', $sArgument);
101
				switch(strtolower($aArg[0])) {
102
					case 'charset':
103
						$this->sCharset = strtolower(preg_replace('/[^a-z0-9]/i', '', $aArg[1]));
104
						break;
105
					case 'tableprefix':
106
						$this->sTablePrefix = $aArg[1];
107
						break;
108
					default:
109
						break;
110
				}
111
			}
112 1866 Luisehahne
			$this->_db_name = $db_name;
113 1680 darkviper
		}else {
114 1885 Luisehahne
			throw new WbDatabaseException('Missing parameter: unable to connect database');
115 1680 darkviper
		}
116 1885 Luisehahne
		$this->_db_handle = @mysql_connect($hostname.$hostport,
117 1887 Luisehahne
		                                   $username,
118 1928 darkviper
		                                   $password,
119
		                                   true);
120 1680 darkviper
		if(!$this->_db_handle) {
121 1885 Luisehahne
			throw new WbDatabaseException('unable to connect \''.$scheme.'://'.
122 1866 Luisehahne
			                           $hostname.$hostport.'\'');
123 4 ryan
		} else {
124 1928 darkviper
			if(!@mysql_select_db($db_name, $this->_db_handle)) {
125 1885 Luisehahne
				throw new WbDatabaseException('unable to select database \''.$db_name.
126 1866 Luisehahne
				                           '\' on \''.$scheme.'://'.
127
				                           $hostname.$hostport.'\'');
128 4 ryan
			} else {
129 1885 Luisehahne
				if($this->sCharset) {
130 1928 darkviper
					@mysql_query('SET NAMES \''.$this->sCharset.'\'', $this->_db_handle);
131 1885 Luisehahne
				}
132 4 ryan
				$this->connected = true;
133
			}
134
		}
135
		return $this->connected;
136
	}
137 1763 Luisehahne
138 4 ryan
	// Disconnect from the database
139 1686 darkviper
	public function disconnect() {
140 95 stefan
		if($this->connected==true) {
141 1680 darkviper
			mysql_close($this->_db_handle);
142 4 ryan
			return true;
143
		} else {
144
			return false;
145
		}
146
	}
147 1763 Luisehahne
148 4 ryan
	// Run a query
149 1686 darkviper
	public function query($statement) {
150 1662 darkviper
		$this->iQueryCount++;
151 4 ryan
		$mysql = new mysql();
152 1680 darkviper
		$mysql->query($statement, $this->_db_handle);
153
		$this->set_error($mysql->error($this->_db_handle));
154
		if($mysql->error($this->_db_handle)) {
155 4 ryan
			return null;
156
		} else {
157
			return $mysql;
158
		}
159
	}
160 1362 Luisehahne
161 4 ryan
	// Gets the first column of the first row
162 1686 darkviper
	public function get_one( $statement )
163 1362 Luisehahne
	{
164 1662 darkviper
		$this->iQueryCount++;
165 1680 darkviper
		$fetch_row = mysql_fetch_array(mysql_query($statement, $this->_db_handle));
166 4 ryan
		$result = $fetch_row[0];
167 1680 darkviper
		$this->set_error(mysql_error($this->_db_handle));
168
		if(mysql_error($this->_db_handle)) {
169 4 ryan
			return null;
170
		} else {
171
			return $result;
172
		}
173
	}
174 1763 Luisehahne
175 4 ryan
	// Set the DB error
176 1686 darkviper
	public function set_error($message = null) {
177 4 ryan
		global $TABLE_DOES_NOT_EXIST, $TABLE_UNKNOWN;
178
		$this->error = $message;
179
		if(strpos($message, 'no such table')) {
180
			$this->error_type = $TABLE_DOES_NOT_EXIST;
181
		} else {
182
			$this->error_type = $TABLE_UNKNOWN;
183
		}
184
	}
185 1763 Luisehahne
186 4 ryan
	// Return true if there was an error
187 1686 darkviper
	public function is_error() {
188 4 ryan
		return (!empty($this->error)) ? true : false;
189
	}
190 1763 Luisehahne
191 4 ryan
	// Return the error
192 1686 darkviper
	public function get_error() {
193 4 ryan
		return $this->error;
194
	}
195 1613 darkviper
/**
196 1885 Luisehahne
 * Protect class from property injections
197
 * @param string name of property
198
 * @param mixed value
199
 * @throws WbDatabaseException
200 1866 Luisehahne
 */
201 1885 Luisehahne
	public function __set($name, $value) {
202
		throw new WbDatabaseException('tried to set a readonly or nonexisting property ['.$name.']!! ');
203 1866 Luisehahne
	}
204
/**
205 1613 darkviper
 * default Getter for some properties
206 1866 Luisehahne
 * @param string name of the Property
207 1613 darkviper
 * @return mixed NULL on error or missing property
208 1362 Luisehahne
 */
209 1613 darkviper
	public function __get($sPropertyName)
210 1362 Luisehahne
	{
211 1613 darkviper
		switch ($sPropertyName):
212
			case 'db_handle':
213
			case 'DbHandle':
214 1662 darkviper
			case 'getDbHandle':
215 1680 darkviper
				$retval = $this->_db_handle;
216 1613 darkviper
				break;
217 1866 Luisehahne
			case 'LastInsertId':
218 1885 Luisehahne
			case 'getLastInsertId':
219 1866 Luisehahne
				$retval = mysql_insert_id($this->_db_handle);
220
				break;
221 1613 darkviper
			case 'db_name':
222
			case 'DbName':
223 1662 darkviper
			case 'getDbName':
224 1680 darkviper
				$retval = $this->_db_name;
225 1613 darkviper
				break;
226 1885 Luisehahne
			case 'TablePrefix':
227
			case 'getTablePrefix':
228
				$retval = $this->sTablePrefix;
229
				break;
230 1662 darkviper
			case 'getQueryCount':
231
				$retval = $this->iQueryCount;
232
				break;
233 1613 darkviper
			default:
234
				$retval = null;
235
				break;
236
		endswitch;
237
		return $retval;
238
	} // __get()
239 1885 Luisehahne
/**
240
 * Escapes special characters in a string for use in an SQL statement
241
 * @param string $unescaped_string
242
 * @return string
243
 */
244
	public function escapeString($unescaped_string)
245
	{
246
		return mysql_real_escape_string($unescaped_string, $this->_db_handle);
247
	}
248
/**
249
 * Last inserted Id
250
 * @return bool|int false on error, 0 if no record inserted
251
 */
252
	public function getLastInsertId()
253
	{
254
		return mysql_insert_id($this->_db_handle);
255
	}
256 1362 Luisehahne
/*
257 1866 Luisehahne
 * @param string full name of the table (incl. TABLE_PREFIX)
258
 * @param string name of the field to seek for
259
 * @return bool true if field exists
260 1362 Luisehahne
 */
261
	public function field_exists($table_name, $field_name)
262
	{
263
		$sql = 'DESCRIBE `'.$table_name.'` `'.$field_name.'` ';
264 1680 darkviper
		$query = $this->query($sql, $this->_db_handle);
265 1362 Luisehahne
		return ($query->numRows() != 0);
266
	}
267
/*
268 1866 Luisehahne
 * @param string full name of the table (incl. TABLE_PREFIX)
269
 * @param string name of the index to seek for
270
 * @return bool true if field exists
271 1362 Luisehahne
 */
272
	public function index_exists($table_name, $index_name, $number_fields = 0)
273
	{
274
		$number_fields = intval($number_fields);
275
		$keys = 0;
276
		$sql = 'SHOW INDEX FROM `'.$table_name.'`';
277 1680 darkviper
		if( ($res_keys = $this->query($sql, $this->_db_handle)) )
278 1362 Luisehahne
		{
279
			while(($rec_key = $res_keys->fetchRow()))
280
			{
281
				if( $rec_key['Key_name'] == $index_name )
282
				{
283
					$keys++;
284
				}
285
			}
286
287
		}
288
		if( $number_fields == 0 )
289
		{
290
			return ($keys != $number_fields);
291
		}else
292
		{
293
			return ($keys == $number_fields);
294
		}
295
	}
296 1763 Luisehahne
297 1362 Luisehahne
/*
298 1866 Luisehahne
 * @param string full name of the table (incl. TABLE_PREFIX)
299
 * @param string name of the field to add
300
 * @param string describes the new field like ( INT NOT NULL DEFAULT '0')
301
 * @return bool true if successful, otherwise false and error will be set
302 1362 Luisehahne
 */
303
	public function field_add($table_name, $field_name, $description)
304
	{
305 1442 Luisehahne
		if( !$this->field_exists($table_name, $field_name) )
306 1362 Luisehahne
		{ // add new field into a table
307
			$sql = 'ALTER TABLE `'.$table_name.'` ADD '.$field_name.' '.$description.' ';
308 1680 darkviper
			$query = $this->query($sql, $this->_db_handle);
309
			$this->set_error(mysql_error($this->_db_handle));
310 1362 Luisehahne
			if( !$this->is_error() )
311
			{
312 1442 Luisehahne
				return ( $this->field_exists($table_name, $field_name) ) ? true : false;
313 1362 Luisehahne
			}
314
		}else
315
		{
316
			$this->set_error('field \''.$field_name.'\' already exists');
317
		}
318
		return false;
319
	}
320
321
/*
322
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
323
 * @param string $field_name: name of the field to add
324
 * @param string $description: describes the new field like ( INT NOT NULL DEFAULT '0')
325
 * @return bool: true if successful, otherwise false and error will be set
326
 */
327
	public function field_modify($table_name, $field_name, $description)
328
	{
329
		$retval = false;
330 1486 DarkViper
		if( $this->field_exists($table_name, $field_name) )
331 1362 Luisehahne
		{ // modify a existing field in a table
332 1486 DarkViper
			$sql  = 'ALTER TABLE `'.$table_name.'` MODIFY `'.$field_name.'` '.$description;
333 1680 darkviper
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false);
334 1486 DarkViper
			$this->set_error(mysql_error());
335 1362 Luisehahne
		}
336 1486 DarkViper
		return $retval;
337 1362 Luisehahne
	}
338
339
/*
340
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
341
 * @param string $field_name: name of the field to remove
342
 * @return bool: true if successful, otherwise false and error will be set
343
 */
344
	public function field_remove($table_name, $field_name)
345
	{
346
		$retval = false;
347 1507 Luisehahne
		if( $this->field_exists($table_name, $field_name) )
348 1362 Luisehahne
		{ // modify a existing field in a table
349
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP `'.$field_name.'`';
350 1680 darkviper
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
351 1362 Luisehahne
		}
352
		return $retval;
353
	}
354
355
/*
356
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
357 1763 Luisehahne
 * @param string $index_name: name of the new index (empty string for PRIMARY)
358 1362 Luisehahne
 * @param string $field_list: comma seperated list of fields for this index
359 1763 Luisehahne
 * @param string $index_type: kind of index (PRIMARY, UNIQUE, KEY, FULLTEXT)
360 1362 Luisehahne
 * @return bool: true if successful, otherwise false and error will be set
361
 */
362 1763 Luisehahne
     public function index_add($table_name, $index_name, $field_list, $index_type = 'KEY')
363
     {
364
        $retval = false;
365 1885 Luisehahne
        $field_list = explode(',', (str_replace(' ', '', $field_list)));
366 1763 Luisehahne
        $number_fields = sizeof($field_list);
367
        $field_list = '`'.implode('`,`', $field_list).'`';
368
        $index_name = $index_type == 'PRIMARY' ? $index_type : $index_name;
369
        if( $this->index_exists($table_name, $index_name, $number_fields) ||
370
            $this->index_exists($table_name, $index_name))
371
        {
372
            $sql  = 'ALTER TABLE `'.$table_name.'` ';
373
            $sql .= 'DROP INDEX `'.$index_name.'`';
374
            if( !$this->query($sql, $this->_db_handle)) { return false; }
375
        }
376
        $sql  = 'ALTER TABLE `'.$table_name.'` ';
377
        $sql .= 'ADD '.$index_type.' ';
378
        $sql .= $index_type == 'PRIMARY' ? 'KEY ' : '`'.$index_name.'` ';
379
        $sql .= '( '.$field_list.' ); ';
380
        if( $this->query($sql, $this->_db_handle)) { $retval = true; }
381
        return $retval;
382
    }
383 1362 Luisehahne
384
/*
385
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
386
 * @param string $field_name: name of the field to remove
387
 * @return bool: true if successful, otherwise false and error will be set
388
 */
389
	public function index_remove($table_name, $index_name)
390
	{
391
		$retval = false;
392
		if( $this->index_exists($table_name, $index_name) )
393
		{ // modify a existing field in a table
394
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP INDEX `'.$index_name.'`';
395 1680 darkviper
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
396 1362 Luisehahne
		}
397
		return $retval;
398
	}
399 1763 Luisehahne
400 1586 darkviper
/**
401
 * Import a standard *.sql dump file
402
 * @param string $sSqlDump link to the sql-dumpfile
403
 * @param string $sTablePrefix
404 1887 Luisehahne
 * @param bool     $bPreserve   set to true will ignore all DROP TABLE statements
405
 * @param string   $sEngine     can be 'MyISAM' or 'InnoDB'
406
 * @param string   $sCollation  one of the list of available collations
407 1586 darkviper
 * @return boolean true if import successful
408
 */
409
	public function SqlImport($sSqlDump,
410
	                          $sTablePrefix = '',
411 1887 Luisehahne
	                          $bPreserve    = true,
412
	                          $sEngine      = 'MyISAM',
413
	                          $sCollation   = 'utf8_unicode_ci')
414 1586 darkviper
	{
415 1887 Luisehahne
		$sCollation = ($sCollation != '' ? $sCollation : 'utf8_unicode_ci');
416
		$aCharset = preg_split('/_/', $sCollation, null, PREG_SPLIT_NO_EMPTY);
417
		$sEngine = 'ENGINE='.$sEngine.' DEFAULT CHARSET='.$aCharset[0].' COLLATE='.$sCollation;
418
		$sCollation = ' collate '.$sCollation;
419 1586 darkviper
		$retval = true;
420
		$this->error = '';
421
		$aSearch  = array('{TABLE_PREFIX}','{TABLE_ENGINE}', '{TABLE_COLLATION}');
422 1887 Luisehahne
		$aReplace = array($this->sTablePrefix, $sEngine, $sCollation);
423 1586 darkviper
		$sql = '';
424
		$aSql = file($sSqlDump);
425 1897 Luisehahne
//		$aSql[0] = preg_replace('/^\xEF\xBB\xBF/', '', $aSql[0]);
426
		$aSql[0] = preg_replace('/^[\xAA-\xFF]{3}/', '', $aSql[0]);
427 1586 darkviper
		while ( sizeof($aSql) > 0 ) {
428
			$sSqlLine = trim(array_shift($aSql));
429 1591 darkviper
			if (!preg_match('/^[-\/]+.*/', $sSqlLine)) {
430 1592 darkviper
				$sql = $sql.' '.$sSqlLine;
431 1586 darkviper
				if ((substr($sql,-1,1) == ';')) {
432
					$sql = trim(str_replace( $aSearch, $aReplace, $sql));
433
					if (!($bPreserve && preg_match('/^\s*DROP TABLE IF EXISTS/siU', $sql))) {
434 1680 darkviper
						if(!mysql_query($sql, $this->_db_handle)) {
435 1586 darkviper
							$retval = false;
436 1680 darkviper
							$this->error = mysql_error($this->_db_handle);
437 1586 darkviper
							unset($aSql);
438
							break;
439
						}
440
					}
441
					$sql = '';
442
				}
443
			}
444
		}
445
		return $retval;
446
	}
447 1362 Luisehahne
448 1586 darkviper
/**
449
 * retuns the type of the engine used for requested table
450
 * @param string $table name of the table, including prefix
451
 * @return boolean/string false on error, or name of the engine (myIsam/InnoDb)
452
 */
453 1535 Luisehahne
	public function getTableEngine($table)
454
	{
455
		$retVal = false;
456 1680 darkviper
		$mysqlVersion = mysql_get_server_info($this->_db_handle);
457 1535 Luisehahne
		$engineValue = (version_compare($mysqlVersion, '5.0') < 0) ? 'Type' : 'Engine';
458 1770 Luisehahne
		$sql = 'SHOW TABLE STATUS FROM `' . $this->_db_name . '` LIKE \'' . $table . '\'';
459 1680 darkviper
		if(($result = $this->query($sql, $this->_db_handle))) {
460 1535 Luisehahne
			if(($row = $result->fetchRow(MYSQL_ASSOC))) {
461
				$retVal = $row[$engineValue];
462
			}
463
		}
464
		return $retVal;
465
	}
466
467
468 1362 Luisehahne
} /// end of class database
469 1885 Luisehahne
// //////////////////////////////////////////////////////////////////////////////////// //
470
/**
471
 * WbDatabaseException
472
 *
473
 * @category     Core
474
 * @package      Core_database
475
 * @author       Werner v.d.Decken <wkl@isteam.de>
476
 * @copyright    Werner v.d.Decken <wkl@isteam.de>
477
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
478
 * @version      2.9.0
479
 * @revision     $Revision$
480
 * @lastmodified $Date$
481
 * @description  Exceptionhandler for the WbDatabase and depending classes
482
 */
483
class WbDatabaseException extends AppException {}
484 1362 Luisehahne
485 1549 Luisehahne
define('MYSQL_SEEK_FIRST', 0);
486
define('MYSQL_SEEK_LAST', -1);
487
488 4 ryan
class mysql {
489
490 1680 darkviper
	private $result = null;
491
	private $_db_handle = null;
492 4 ryan
	// Run a query
493 1680 darkviper
	function query($statement, $dbHandle) {
494
		$this->_db_handle = $dbHandle;
495 1889 Luisehahne
		$this->result = @mysql_query($statement, $this->_db_handle);
496
		if($this->result === false) {
497
			if(DEBUG) {
498
				throw new WbDatabaseException(mysql_error($this->_db_handle));
499
			}else{
500
				throw new WbDatabaseException('Error in SQL-Statement');
501
			}
502
		}
503 1680 darkviper
		$this->error = mysql_error($this->_db_handle);
504 4 ryan
		return $this->result;
505
	}
506 1763 Luisehahne
507 4 ryan
	// Fetch num rows
508
	function numRows() {
509
		return mysql_num_rows($this->result);
510
	}
511 1011 Ruebenwurz
512
	// Fetch row  $typ = MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
513
	function fetchRow($typ = MYSQL_BOTH) {
514
		return mysql_fetch_array($this->result, $typ);
515 4 ryan
	}
516 1011 Ruebenwurz
517 1549 Luisehahne
	function rewind()
518
	{
519
		return $this->seekRow();
520
	}
521
522
	function seekRow( $position = MYSQL_SEEK_FIRST )
523
	{
524
		$pmax = $this->numRows() - 1;
525
		$p = (($position < 0 || $position > $pmax) ? $pmax : $position);
526
		return mysql_data_seek($this->result, $p);
527
	}
528
529 4 ryan
	// Get error
530
	function error() {
531
		if(isset($this->error)) {
532
			return $this->error;
533
		} else {
534
			return null;
535
		}
536
	}
537
538
}
539 1885 Luisehahne
// //////////////////////////////////////////////////////////////////////////////////// //
540 1364 Luisehahne
/* this function is placed inside this file temporarely until a better place is found */
541
/*  function to update a var/value-pair(s) in table ****************************
542
 *  nonexisting keys are inserted
543
 *  @param string $table: name of table to use (without prefix)
544
 *  @param mixed $key:    a array of key->value pairs to update
545
 *                        or a string with name of the key to update
546
 *  @param string $value: a sting with needed value, if $key is a string too
547
 *  @return bool:  true if any keys are updated, otherwise false
548
 */
549
	function db_update_key_value($table, $key, $value = '')
550
	{
551
		global $database;
552
		if( !is_array($key))
553
		{
554
			if( trim($key) != '' )
555
			{
556
				$key = array( trim($key) => trim($value) );
557
			} else {
558
				$key = array();
559
			}
560
		}
561
		$retval = true;
562
		foreach( $key as $index=>$val)
563
		{
564
			$index = strtolower($index);
565 1680 darkviper
			$sql = 'SELECT COUNT(`setting_id`) '
566
			     . 'FROM `'.TABLE_PREFIX.$table.'` '
567
			     . 'WHERE `name` = \''.$index.'\' ';
568 1364 Luisehahne
			if($database->get_one($sql))
569
			{
570
				$sql = 'UPDATE ';
571
				$sql_where = 'WHERE `name` = \''.$index.'\'';
572
			}else {
573
				$sql = 'INSERT INTO ';
574
				$sql_where = '';
575
			}
576
			$sql .= '`'.TABLE_PREFIX.$table.'` ';
577
			$sql .= 'SET `name` = \''.$index.'\', ';
578
			$sql .= '`value` = \''.$val.'\' '.$sql_where;
579
			if( !$database->query($sql) )
580
			{
581
				$retval = false;
582
			}
583
		}
584
		return $retval;
585
	}