<?php
class class_db
{
	function db()
	{
		if( !( $this->sql_connect = mysqli_connect(HOSTNAME, USERNAME, PASSWORD) ) )
			exit('Server connection failed!!');
		else if( !mysqli_select_db($this->sql_connect, DATABASENAME) )
			exit('Database connection failed!!');

		mysqli_query($this->sql_connect, 'SET NAMES UTF8');
		mysqli_query($this->sql_connect, 'SET CHARACTER_SET_RESULTS=UTF8'); 
	}

	function result_setto_array($static_sql_result)
	{
		$arr_return = array();

		$i_max = mysqli_num_rows($static_sql_result);
		for( $i=0; $i<$i_max; $i++ )
		{
			if( $arr_row = mysqli_fetch_assoc($static_sql_result) )
				array_push($arr_return, $arr_row);
			else
				break;
		}

		mysqli_free_result($static_sql_result);
		return($arr_return);
	}	

	function write_error_logs($static_str_tsql)
	{
		$str_filename = 'error_logs/error_' . date('ymd') . '.log';
		if( $file_handle = fopen($str_filename, 'a') )
		{
			$str_error_log = date('H:i:s') . ' ' . $_SERVER['PHP_SELF'] . ' [' . $_SERVER['REMOTE_ADDR'] . ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] ? (' via ' . $_SERVER['HTTP_X_FORWARDED_FOR']) : '' ) . '] mysqli_errno=' . mysqli_errno($this->sql_connect) . ' ' . mysqli_error($this->sql_connect) . ' tsql=' . $static_str_tsql . " \r\n";
			fwrite($file_handle, $str_error_log);

			fclose($file_handle);
		}
	}

	function page_info($static_str_count_column, $static_str_table_name, $static_str_condition, $static_uint_row_pp)
	{
		$str_query = 'SELECT COUNT(' . $static_str_count_column . ') AS `RowCount` 
		FROM `' . $static_str_table_name . '` 
		WHERE ' . $static_str_condition . ' ';
		if( !( $sql_result = mysqli_query($this->sql_connect, $str_query) ) )
		{
			$this->write_error_logs($str_query);
			return false;
		}
		else if( !( $arr_result = mysqli_fetch_assoc($sql_result) ) )
		{
			mysqli_free_result($sql_result);
			return null;
		}
		else
		{
			mysqli_free_result($sql_result);

			$uint_row_count = (int)$arr_result['RowCount'];
			$uint_page_count = floor( ( $uint_row_count - 1 ) / $static_uint_row_pp ) + 1;

			return array('RowCount'=>$uint_row_count, 'PageCount'=>$uint_page_count);
		}
	}
}
?>
