<?php

	if (!defined('IN_HUGLO')) {
		exit;
	}
	
	class db {
		var $sql_id;
		var $server = '';
		var $user = '';
		var $base = '';
		var $persistant = false;
		
		function sql_connect($sql_server, $sql_user, $sql_passwd, $sql_base, $sql_port = false, $sql_persistant = false, $sql_link = false) {
			$this->server = $sql_server . (($sql_port) ? ':' . $sql_port : '');
			$this->user = $sql_user;
			$this->base = $sql_base;
			$this->persistant = $sql_persistant;
	
			if($this->persistant === false) {
				$this->sql_id = @mysql_connect($this->server, $this->user, $sql_passwd, $sql_link);
			} else {
				$this->sql_id = @mysql_pconnect($this->server, $this->user, $sql_passwd, $sql_link);
			}
	
			if($this->sql_id and $this->base != '') {
				if(@mysql_select_db($this->base, $this->sql_id)) {
					$result = mysql_query('SELECT VERSION() AS version', $this->sql_id);
					$row = @mysql_fetch_assoc($result);
					@mysql_free_result($result);
					if(version_compare($row['version'], '4.1.3', '>=')) {
						@mysql_query("SET NAMES 'utf8'", $this->sql_id);
					}
					return $this->sql_id;
				} else {
					return false;
				}
			} else {
				return false;
			}
		}
	
		function sql_insert_update($query, $array_assoc = false) {
			if(!is_array($array_assoc)) {
				return false;
			}
			
			$fields = $values = array();
			
			if($query == 'INSERT') {
				foreach($array_assoc as $key => $var) {
					$fields[] = $key;
					$values[] = $this->_sql_valide_value($var);
				}
				
				$query = ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
			} elseif ($query == 'UPDATE') {
				foreach ($array_assoc as $key => $var)
				{
					$values[] = "$key = " . $this->_sql_valide_value($var);
				}
	
				$query = implode(', ', $values);
			} else {
				return false;
			}
			
			return $query;
		}
	
		function sql_close() {
			if($this->sql_id) {
				if($result = @mysql_close($this->sql_id)) {
					$this->sql_id = false;
				} else {
					return false;
				}
			} else {
				return false;
			}
			
			return $result;
		}
		
		function _sql_valide_value($var) {
			if (is_null($var)) {
				return 'NULL';
			} else if (is_string($var)) {
				return "'" . $this->_sql_escape($var) . "'";
			} else {
				return (is_bool($var)) ? intval($var) : $var;
			}
		}
		
		function _sql_escape($string) {
			if($this->sql_id) {
				return @mysql_real_escape_string(stripslashes($string), $this->sql_id);
			} else {
				return @mysql_real_escape_string(stripslashes($string));
			}
		}
		
		function _sql_error() {
			if($this->sql_id) {
				return @mysql_errno($this->sql_id) . ' : ' . @mysql_error($this->sql_id);
			} else {
				return @mysql_errno() . ' : ' . @mysql_error();
			}
		}
	}

?>