<?php
require_once(searchinc('utils1.inc'));

define('DEFAULT_TRIGGER_ON_ERROR', -1);
define('TRIGGER_ON_ERROR', 1);
define('NO_TRIGGER_ON_ERROR', 0);

define('DEBUG_MINUTIA_TRACE',6);
define('DEBUG_DETAIL_TRACE', 5);
define('DEBUG_PROC_TRACE', 4);
define('DEBUG_SHOW_WARNINGS', 3);
define('DEBUG_SHOW_ERRORS', 2);
define('DEBUG_SHOW_ABORTS', 1);
define('DEBUG_NONE', 0);

define('RETURN_NULL_OK', true);

function base_obj_in_array($base_obj, $haystack)
{
	if (!is_a($base_obj, 'base')) {return false;}
	if (!is_array($haystack)) {return false;}
	$keys = array_keys($haystack);
	foreach($keys as $key)
	{
		if ($base_obj->is_me($haystack[$key])) {return true;}
	}
	return false;
}

class base
{
	var $_errs;
	var $_mode;
	var $_instance;
	var $_tagid;
        var $_debug;
        
        var $_mode_stk = array();
	
	private static $_instance_counter = 0;
	
	function __sleep()
	{
		// return all members that are not resources
		$objectKeys = array_keys(get_object_vars($this));
		$serializeVars = array();
		
		foreach ($objectKeys as $key)
		{
			if (!is_resource($this->$key)) {$serializeVars[] = $key;}
		}
		
		return $serializeVars;
	}
	
	function __wakeup()
	{
		// nothing to do as the default is for resources to
		// have wrappers that re-connect themselves
	}
	
	function instance()
	{
		return $this->_instance;
	}
		
	function tag()
	{
		if (!isset($this->_tagid))
		{
			$seed = mt_rand_str(256).date('YmdwHis').$this->_instance;
			if (function_exists('mhash'))
			{
				$this->_tagid = mhash(MHASH_SHA1, $seed);
			}
			else if (function_exists('hash'))
			{
				$this->_tagid = hash('sha1', $seed);
			}
			else
			{
				$this->_tagid = sha1($seed);
			}
		};
			
		return $this->_tagid;
	}

	function base_default_mode($new=null)
	{
		static $base_default_mode = NO_TRIGGER_ON_ERROR;
		
		$res = true;
		if (isset($new))
		{
			$res = false;
			if (($new == TRIGGER_ON_ERROR) || ($new == NO_TRIGGER_ON_ERROR))
			{
				$base_default_mode = $new;
				$res = true;
			}
		}
		
		return ($res?$base_default_mode:false);
	}
	
	public function __construct($mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$mode.') entered', DEBUG_PROC_TRACE);
		
		$this->_mode = (DEFAULT_TRIGGER_ON_ERROR===$mode?base::base_default_mode():$mode);
		$this->_instance = self::$_instance_counter++;
//		$this->_instance = static::_instance_counter++;
//		$this->_instance = $this->_instance_counter++;
		
		$this->dbgecho($proc.' mode - '.$this->_mode, DEBUG_DETAIL_TRACE);
		$this->dbgecho($proc.' leaving - succeeded', DEBUG_PROC_TRACE);
//		return true;
	}
	
	function is_me($obj)
	{
		return (is_object($obj) && (get_class($obj) == get_class($this)) && ($obj->_instance === $this->_instance));
	}
        
        function push_mode($new)
        {
            array_push($this->_mode_stk, $this->_mode);
            $this->_mode = $new;
        }
        
        function pop_mode()
        {
            if (count($this->_mode_stk)==0)
            {
                $this->set_error('Pop from empty mode statck attempted.', __FILE__, __LINE__);
            }
            else
            {
                $this->_mode = array_pop($this->_mode_stk);
            }
            if (($this->_mode == TRIGGER_ON_ERROR) && (count($this->_errs) > 0))
            {
                $this->trigger_error();
            }
        }
	
	function clear_error()
	{
		unset($this->_errs);
	}
	
	function is_ok($val=null,$retnul=false)
	{
		return (isset($this->_errs)?false:($retnul?$val:(isset($val)?$val:true)));
	}
	
	function set_error($msg, $file, $line)
	{
		if (!isset($this->_errs)){ $this->_errs = array(); }
		$this->static_set_error($this->_errs, $msg, $file, $line, $this->debug());
		if ($this->_mode == TRIGGER_ON_ERROR)
		{
			$this->trigger_error();
		}
	}
	
	static public function static_set_error(&$errs, $msg, $file, $line, $debug=DEBUG)
	{
		if (!is_array($errs)){ $errs = array(); }
		$errs[count($errs)] = array('msg' => $msg, 'file' => $file, 'line' => $line);
		$err = $errs[count($errs)-1];
		base::static_dbgecho('USER ERROR: '.$err['msg'].' at line #'.$err['line'].' in '.$err['file'], DEBUG_SHOW_ERRORS, $debug);
	}
	
	static public function static_get_full_error($errs, $idx=null)
	{
		if (!isset($errs)) {return null;}
		if (!isset($idx) || ($idx>count($errs)-1))
		{
			$idx = count($errs)-1;
		}
		else if ($idx < 0)
		{
			$idx = 0;
		}
		$err = $errs[$idx];
		return $err['msg'].' at line #'.$err['line'].' in '.$err['file'];
	}
	
	static public function static_get_extended_error($errs)
	{
		if (!isset($errs)) {return null;}
		$idx = count($errs)-1;
		$errtxt = '';
		while($idx >= 0)
		{
			if (strlen($errtxt) > 0) {$errtxt .= "\n";}
			$errtxt .= base::static_get_full_error($errs, $idx);
			$idx--;
		}
		return $errtxt;
	}
	
	static public function static_get_error_nesting($errs)
	{
		return (isset($errs)?count($errs):0);
	}
	
	function get_error_nesting()
	{
		return base::static_get_error_nesting($this->_errs);
	}
	
	function get_error($idx=null)
	{
		if (!isset($this->_errs)) {return null;}
		if (!isset($idx) || ($idx>count($this->_errs)-1))
		{
			$idx = count($this->_errs)-1;
		}
		else if ($idx < 0)
		{
			$idx = 0;
		}
		return $this->_errs[$idx]['msg'];
	}
	
	function get_error_file($idx=null)
	{
		if (!isset($this->_errs)) {return null;}
		if (!isset($idx) || ($idx>count($this->_errs)-1))
		{
			$idx = count($this->_errs)-1;
		}
		else if ($idx < 0)
		{
			$idx = 0;
		}
		return $this->_errs[$idx]['file'];
	}
	
	function get_error_line($idx=null)
	{
		if (!isset($this->_errs)) {return null;}
		if (!isset($idx) || ($idx>count($this->_errs)-1))
		{
			$idx = count($this->_errs)-1;
		}
		else if ($idx < 0)
		{
			$idx = 0;
		}
		return $this->_errs[$idx]['line'];
	}
	
	function get_full_error($idx=null)
	{
		return base::static_get_full_error($this->_errs, $idx);
	}
	
	function get_extended_error()
	{
		return base::static_get_extended_error($this->_errs);
	}
	
	function trigger_error()
	{
		trigger_error(nl2br($this->get_extended_error()), E_USER_ERROR);
	}
	
	function trigger_warning($text)
	{
		trigger_error($text, E_USER_WARNING);
	}
	
	function trigger_notice($text)
	{
		trigger_error($text, E_USER_NOTICE);
	}
	
	function copy_error($obj)
	{
		$this->_errs = $obj->_errs;
	}
	
	function save_error()
	{
		return $this->_errs;
	}
	
	function restore_error($errs)
	{
		$this->_errs = $errs;
	}
	
	function debug()
	{
		return max($this->_debug, DEBUG);
	}
	
	function set_debug_log($filename)
	{
		if (!isset($GLOBALS['base_debug_log_hndl']))
		{
			$GLOBALS['base_debug_log_name'] = $filename;
		}
		return ($GLOBALS['base_debug_log_name'] === $filename);
	}
	
	function get_debug_log()
	{
		return $GLOBALS['base_debug_log_name'];
	}
	
	function dbgecho($text, $level=1)
	{
		base::static_dbgecho($text, $level, $this->debug());
	}
	
	static public function static_dbgecho($text, $level=DEBUG_SHOW_ABORTS, $debug=null)
	{
		if (!isset($debug)) {$debug=DEBUG;}
		if ($debug && ($level<=$debug))
		{
			if (!isset($GLOBALS['base_debug_log_hndl']))
			{
				if (isset($GLOBALS['base_debug_log_name']))
				{
					$GLOBALS['base_debug_log_hndl'] = fopen($GLOBALS['base_debug_log_name'], 'a');
					if ($GLOBALS['base_debug_log_hndl'] === false)
					{
						unset($GLOBALS['base_debug_log_hndl']);
					}
				}
			}
			if (!isset($GLOBALS['base_debug_log_hndl']) || ($GLOBALS['base_debug_log_hndl']==false))
			{
				echo '<!-- '.$text.' -->'."\n";
			}
			else
			{
				list($usec, $sec) = explode(' ', microtime());
				fwrite($GLOBALS['base_debug_log_hndl'], '['.date('m/d/y H:i:s').substr($usec, 1, 5).' ('.$debug.')] '.$text."\n");
			}
		}
	}
	
	function copyfrom($object)
	{
		if (!is_a($object, get_class($this)))
		{
			$this->set_error('Attempt to copy from incompatable class.', __FILE__, __LINE__);
		}
		else
		{
			$vars = get_object_vars($this);
			foreach($vars as $key => $val)
			{
				$this->$key = $object->$key;
			}
		}
		
		return $this->is_ok();
	}
	
	function do_once_for_class($what)
	{
		static $flags = array();
		
		if ($doit = (!isset($flags[$what])))
		{
			$flags[$what] = 1;
		}
		
		return $doit;
	}
}

class dbresult extends base
{
	protected $_res;
	
	function __construct($res, $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		parent::__construct($mode);
		$this->_res = $res;
	}

	function num_rows()
	{
//		$this->clear_error();
//		if (false===($num = mysqli_num_rows($this->_res)))
//		{
//			$this->set_error('sql num rows error ['.mysqli_errno().'] '.mysqli_error(), __FILE__, __LINE__);
//		}
//		return $this->is_ok($num);
                return mysqli_num_rows($this->_res);
	}
	
	function fetch_row()
	{
		return mysqli_fetch_row($this->_res);
	}
	
	function fetch_array()
	{
		return mysqli_fetch_assoc($this->_res);
	}
	
	function fetch_data()
	{
		$this->clear_error();
		
		$datarray = array();
		while ($row = $this->fetch_array())
		{
			$datarray[] = $row;
		}
		
		return $this->is_ok($datarray);
	}
	
	function fetch_column($col_idx=0)
	{
		$this->clear_error();
		
		$datarray = array();
		while ($row = $this->fetch_row())
		{
			$datarray[] = $row[$col_idx];
		}
		
		return $this->is_ok($datarray);
	}
	
	function fetch_one()
	{
		if ($rows = $this->fetch_column())
		{
			if (count($rows) > 1) {trigger_warning('Multiple records found.  Ignoring all but first.');}
		}
		
		return $this->is_ok($rows[0], RETURN_NULL_OK);
	}
	
	function free()
	{
		$this->clear_error();
		mysqli_free_result($this->_res);
		return $this->is_ok();
	}
}

define('DBCONN_LOG', $GLOBALS['NEOFSUS_BASEDIR'].'/debug/dbconns.log');
//define('DBCONN_LOG', $GLOBALS['NEOFSUS_BASEDIR'].'/springalive/test/dbconns.log');
class basedb extends base
{
	var $_dblink;
	var $_user;
	var $_password;
	var $_default_dbase;
	var $_host;
	
	function _ensure_tables_exist()
	{
		return true;
	}
	
	static public function _close_all_db_connections()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		base::static_dbgecho($proc.'entering', DEBUG_PROC_TRACE, DEBUG);
		
		if (is_array($GLOBALS['_basedb_db_conns_']))
		{
			$dbhosts = array_keys($GLOBALS['_basedb_db_conns_']);
			
			base::static_dbgecho($proc.'db connections for '.count($dbhosts).' hosts to close', DEBUG_DETAIL_TRACE, DEBUG);
			
			foreach ($dbhosts as $dbhost)
			{
				$dbnames = array_keys($GLOBALS['_basedb_db_conns_'][$dbhost]);
				
				base::static_dbgecho($proc.'host '.$dbhost.' - '.count($dbnames).' db connections to close', DEBUG_DETAIL_TRACE, DEBUG);
				
				$i = 0;
				foreach ($dbnames as $dbname)
				{
					base::static_dbgecho($proc.'shutdown_function: closing connection for '.$dbname.' ('.$i++.')', DEBUG_DETAIL_TRACE, DEBUG);
					if (mysqli_close($GLOBALS['_basedb_db_conns_'][$dbhost][$dbname]))
					{
						base::static_dbgecho($proc.'succeeded closing '.$dbname, DEBUG_DETAIL_TRACE, DEBUG);
						unset($GLOBALS['_basedb_db_conns_'][$dbhost][$dbname]);
					}
					else
					{
						base::static_dbgecho($proc.'failed closing '.$dbname, DEBUG_DETAIL_TRACE, DEBUG);
					}
				}
				unset($GLOBALS['_basedb_db_conns_'][$dbhost]);
			}
		}
		else
		{
			base::static_dbgecho($proc.'no db connections to close', DEBUG_PROC_TRACE, DEBUG);
//			logmsg('no db connections to close', DBCONN_LOG);
		}
		base::static_dbgecho($proc.'leaving', DEBUG_PROC_TRACE, DEBUG);
	}
	
	function __construct($dbname, $user, $password, $host=null, $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
//                $this->_debug = DEBUG_DETAIL_TRACE;
                
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$dbname.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		parent::__construct($mode);

		$this->_user = $user;
		$this->_password = $password;
		if (isset($host))
		{
			$this->_host = $host;
		}
		if (!isset($this->_host))
		{
			if (isset($GLOBALS['default_mysql_host']))
			{
				$this->_host = $GLOBALS['default_mysql_host'];
			}
			else
			{
				$this->_host = 'localhost';
			}
		}
			
		if ($this->select_db($dbname))
		{
			if ($this->do_once_for_class('ensure_tables_exist'))
			{
				$this->_ensure_tables_exist();
			}
			if ($this->do_once_for_class('register_shutdown_function'))
			{
                                $this->dbgecho($proc.' registering shutdown function '.get_class($this).'::_close_all_db_connections', DEBUG_PROC_TRACE);
				register_shutdown_function(array(__CLASS__, '_close_all_db_connections'));
			}
		}
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
	}
	
	function select_db($dbname)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$dbname.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (empty($dbname)) {$dbname = $this->_default_dbase;}
		
		// if a connection to this database already exists, use that one
		if (isset($GLOBALS['_basedb_db_conns_'][$this->_host][$dbname]))
		{
			$this->_dblink = $GLOBALS['_basedb_db_conns_'][$this->_host][$dbname];
			$this->dbgecho($proc.'db link obtained from cache', DEBUG_DETAIL_TRACE);
		}
		else
		{
			// otherwise, create a new connection
			if ($GLOBALS['_basedb_db_conns_'][$this->_host][$dbname] = $this->DBlink(true))
			{
//				logmsg('created connection for '.$dbname, DBCONN_LOG);
				$this->dbgecho($proc.'native db link created', DEBUG_DETAIL_TRACE);
				if (isset($dbname) && !mysqli_select_db($GLOBALS['_basedb_db_conns_'][$this->_host][$dbname], $dbname))
				{
					$this->dbgecho($proc.'unable to select database '.$dbname, DEBUG_DETAIL_TRACE);
					$this->set_error('sql select db error ['.mysqli_errno($GLOBALS['_basedb_db_conns_'][$this->_host][$dbname]).'] '.
                                                                                 mysqli_error($GLOBALS['_basedb_db_conns_'][$this->_host][$dbname]), __FILE__, __LINE__);
//					logmsg('select_db failed: cleaning connection for '.$dbname.' - ', DBCONN_LOG, false);
					if (mysqli_close($GLOBALS['_basedb_db_conns_'][$this->_host][$dbname]))
					{
//						logmsg('succeeded', DBCONN_LOG);
						unset($GLOBALS['_basedb_db_conns_'][$this->_host][$dbname]);
					}
					else
					{
//						logmsg('failed', DBCONN_LOG);
					}
				}
				else
				{
					$this->dbgecho($proc.'database '.$dbname.' selected', DEBUG_DETAIL_TRACE);
				}
			}
			else
			{
				$this->dbgecho($proc.'unable to create native db link', DEBUG_DETAIL_TRACE);
				unset($GLOBALS['_basedb_db_conns_'][$this->_host][$dbname]);
			}
		}
		if ($this->is_ok())
		{
			$this->_default_dbase = $dbname;
		}
		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function get_db()
	{
		return $this->_default_dbase;
	}
	
	function get_db_user()
	{
		return $this->_user;
	}
	
	function DBlink($mkunique=false)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.($mkunique?'unique':'shared').') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$this->dbgecho($proc.'host='.$this->_host.', user='.$this->_user, DEBUG_DETAIL_TRACE);
                
		if ($mkunique)
		{
			if (!$this->_dblink = mysqli_connect($this->_host, $this->_user, $this->_password))
			{
				$this->dbgecho($proc.'unable to create unique db link', DEBUG_DETAIL_TRACE);
				$this->set_error('sql connect error ['.mysqli_connect_errno().'] '.mysqli_connect_error(), __FILE__, __LINE__);
			}
			else
			{
				$this->dbgecho($proc.'unique db link created:'.look_r($this->_dblink), DEBUG_DETAIL_TRACE);
			}
		}
		elseif (!isset($this->_dblink))
		{
			$this->dbgecho($proc.'get a shared db link with no selected database', DEBUG_DETAIL_TRACE);
			$this->select_db(null);
			$this->dbgecho($proc.'shared db link found:'.look_r($this->_dblink), DEBUG_DETAIL_TRACE);
		}
		// verify that our link is still good
//		if (get_resource_type($this->_dblink) === "Unknown")//		if (get_resource_type($this->_dblink) === "Unknown")
		if (!is_object($this->_dblink) || !is_a($this->_dblink, 'mysqli') /* || !mysqli_query($this->_dblink, 'DO 1') or try mysqli_get_server_info() */ ) // if link still represents an open connection
		{
			$this->dbgecho($proc.'db link has been invalidated.  Try to get a new one.', DEBUG_DETAIL_TRACE);
			// try to get a new one
			
			if (!$this->_dblink = mysqli_connect($this->_host, $this->_user, $this->_password))
			{
				$this->dbgecho($proc.'unable to re-create invalidated db link', DEBUG_DETAIL_TRACE);
				$this->set_error('sql connect error ['.mysqli_connect_errno().'] '.mysqli_connect_error(), __FILE__, __LINE__);
			}
			else
			{
				// re-establish the database selection, but don't call select_db() to avoid an endless recursion possibility
				if (mysqli_select_db($this->_dblink, $this->_default_dbase))
				{
					$GLOBALS['_basedb_db_conns_'][$this->_host][$this->_default_dbase] = $this->_dblink;
				}
			}
		}

		$this->dbgecho($proc.'leaving - '.($this->is_ok()?'succeeded: ':'failed'.': ')/* .look_r($this->_dblink) */, DEBUG_PROC_TRACE);
		return $this->is_ok($this->_dblink);
	}
	
	function query($querystr)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->clear_error();
		$this->dbgecho($proc.'entering: query='.$querystr, DEBUG_PROC_TRACE);
		
                $dblink = $this->DBLink();
		$res = mysqli_query($dblink, $querystr);
		$this->dbgecho($proc.'$res: '.look_r($res), DEBUG_DETAIL_TRACE);
		if ($res === FALSE)
		{
			$this->set_error('query error in '.$querystr.' - '.mysqli_errno($dblink).': '.mysqli_error($dblink), __FILE__, __LINE__);
		}
//		else if (is_resource($res))
		else if (is_object($res) && is_a($res, 'mysqli_result'))
		{
			$res = new dbresult($res);
			if (!$res->is_ok())
			{
				$this->copy_error($res);
			}
		}
		$this->dbgecho($proc.'leaving: '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($res);
	}
	
	function last_insert_id()
	{
		return mysqli_insert_id($this->DBlink());
	}
	
	function affected_rows()
	{
		return mysqli_affected_rows($this->DBlink());
	}
	
	function num_rows($res)
	{
		$this->clear_error();
		$num = $res->num_rows();
		if (!$res->is_ok())
		{
			$this->copy_error($res);
		}
		return $this->is_ok($num);
	}
	
	function fetch_row($res)
	{
		$this->clear_error();
		$row = $res->fetch_row();
		if (!$res->is_ok())
		{
			$this->copy_error($res);
		}
		return $this->is_ok($row);
	}
	
	function fetch_array($res)
	{
		$this->clear_error();
		$row = $res->fetch_array();
		if (!$res->is_ok())
		{
			$this->copy_error($res);
		}
		return $this->is_ok($row);
	}
	
	function free_result($res)
	{
		$this->clear_error();
		$res->free();
		if (!$res->is_ok())
		{
			$this->copy_error($res);
		}
		return $this->is_ok();
	}
	
	function escape_string($text)
	{
		if (isset($text))
		{
			if (function_exists('mysqli_real_escape_string'))
			{
				return mysqli_real_escape_string($this->DBlink(), $text);
			}
			else
			{
				return mysqli_escape_string($text);
			}
		}
		return null;
	}
	
	function create_tmp_table($sourcetable, $fields, $criteria=NULL, $index=NULL)
	{
		$this->clear_error();
		// create a unique table name
		$table = 'tt'.mt_rand(10000000, 99999999);
		while (mysqli_query($this->_dblink, 'SELECT 1 FROM '.$table.' LIMIT 0'))
		{
			$table = 'tt'.mt_rand(1000000000, 9999999999);
		}
		$query = 'CREATE TEMPORARY TABLE '.$table;
		if (isset($index)) {$query .= ' (INDEX ('.$index.'))';}
		$query .= ' SELECT '.$fields.' FROM '.$sourcetable;
		if (isset($criteria)) {$query .= ' WHERE '.$criteria;}
		$this->query($query);
		return $this->is_ok($table);
	}
	
	function free_tmp_table($name)
	{
		$this->clear_error();
		if ((substr($name,0,2)!='tt') || (0+substr($name,2)<1000000000) || (0+substr($name,2)>9999999999))
		{
			$this->set_error('invalid temporary table name: '.$name, __FILE__, __LINE__);
		}
		else
		{
			$this->query('DROP TABLE '.$name);
		}
		return $this->is_ok();
	}
	
	function lock_table($tablename)
	{
		$this->clear_error();
		$query = 'LOCK TABLES '.$tablename.' WRITE';
		$this->query($query);
		return $this->is_ok();
	}
	
	function unlock_table()
	{
		$this->clear_error();
		$query = 'UNLOCK TABLES';
		$this->query($query);
		return $this->is_ok();
	}
	
	function query_data($querystr)
	{
		$this->clear_error();
		
		if ($res = $this->query($querystr))
		{
			$val = $res->fetch_data();
			if (!$res->is_ok())
			{
				$this->copy_error($res);
			}
			$res->free();
		}
		
		return $this->is_ok($val);
	}
	
	function query_column($querystr, $col_idx=0)
	{
		$this->clear_error();
		
		if ($res = $this->query($querystr))
		{
			$val = $res->fetch_column($col_idx);
			if (!$res->is_ok())
			{
				$this->copy_error($res);
			}
			$res->free();
		}
		
		return $this->is_ok($val);
	}
	
	function query_row($querystr)
	{
		$this->clear_error();
		
		if ($res = $this->query($querystr))
		{
			$val = $res->fetch_row();
			if (!$res->is_ok())
			{
				$this->copy_error($res);
			}
			$res->free();
		}
		
		return $this->is_ok($val, RETURN_NULL_OK);
	}
	
	function query_one($querystr)
	{
		$this->clear_error();
		
		if ($res = $this->query($querystr))
		{
			$val = $res->fetch_one();
			if (!$res->is_ok())
			{
				$this->copy_error($res);
			}
			$res->free();
		}
		
		return $this->is_ok($val, RETURN_NULL_OK);
	}
}
 ?>