Location: PHPKode > projects > Esvon Personals > esvon-personals/inc/class.mysql.php
<?php

// --------------------------------------------------------------------------
//
// Esvon Classifieds v.4.0
// Copyright(C), Esvon LTD, 2001-2010, All Rights Reserved.
// E-mail: hide@address.com
//
// All forms of reproduction, including, but not limited to, internet posting, 
// printing, e-mailing, faxing and recording are strictly prohibited.
// One license required per site running Esvon Classifieds. 
// To obtain a license for using Esvon Classifieds, please register at
// http://www.esvon.com/pg/products/p_classifieds/
//
// --------------------------------------------------------------------------

if(!function_exists('mysql_connect')){ 

  if(function_exists('mysqli_connect')) { // MySQLi workaround

    function mysql_connect($server,$user,$pass){ return mysqli_connect($server,$user,$pass); }
    function mysql_fetch_row($res) { return mysqli_fetch_row($res); }
    function mysql_fetch_assoc($res) { return mysqli_fetch_assoc($res); }
    function mysql_data_seek($res,$i) { return mysqli_data_seek($res,$i); }
    function mysql_free_result($res) { return mysqli_free_result($res); }
    function mysql_num_rows($res) { return mysqli_num_rows($res); }
    function mysql_error($conn = null) { return $conn ? mysqli_error($conn) : mysqli_connect_error(); }
    function mysql_errno($conn = null) { return $conn ? mysqli_errno($conn) : mysqli_connect_errno(); }
    function mysql_real_escape_string($s, $conn) { return mysqli_real_escape_string($conn, $s); }
    function mysql_query($sql, $conn) { return mysqli_query($conn, $sql); }
    function mysql_insert_id($conn) { return mysqli_insert_id($conn); }
    function mysql_affected_rows($conn) { return mysqli_affected_rows($conn); }
    function mysql_get_server_info($conn) { return mysqli_get_server_info($conn); }
    function mysql_select_db($name,$conn) { return mysqli_select_db($conn, $name); }
    function mysql_num_fields($res) { return mysqli_num_fields($res); }
    function mysql_field_name($res, $i){
      mysqli_field_seek($res,$i);
      $finfo = mysqli_fetch_field($res);
      return $finfo->name;
    }
  }
  elseif(class_exists('PDO')){
    include SITE_PATH.'inc/pdo.inc.php'; // experimental layer
  }
}

// if PHP < 4.3.0
if(!function_exists('mysql_real_escape_string')){
  function mysql_real_escape_string($s, $conn){ return mysql_escape_string($s); }
}

class Es_DB_Stats {
	
	var $a_sql = array();
  var $a_time = array();
	var $a_mem = array();
  var $o_tm;
  
  function logSQL($sql){ 
    //$sql.=' /* '.$this->_stack_trace().' */';
    $this->a_sql[] = $sql; 
  }
  function startQuery(){
    $this->o_tm = &Factory::create('HwTimer');
    $this->o_tm->startTimer();
  }
  function endQuery(){ 
    $this->a_time[] = $this->o_tm->endTimer();
    if(function_exists('memory_get_usage')) $this->a_mem[] = memory_get_usage();
  }
  function _stack_trace(){
    $stack = array();
    $trace = debug_backtrace();
    array_splice($trace, 0, 3);
    // push each function onto the stack
    $len = strlen(SITE_PATH);
    foreach($trace as $t) $stack[] = $t['function'].'() ['.substr($t['file'],$len).']';
    $stack = array_reverse($stack);
    return implode(' > ', $stack);
  }
}

class Database {

	var $CONN = '';
	var $CURDB = '';
	var $ERR_EXIT = TRUE;
	var $ERR_MSG = '';

  var $DEBUG = FALSE;
  
  var $o_stats;
  var $is_1st_obj = TRUE;

  function Database(){
    $this->DEBUG = (EN_DEBUG_SQL==1 && $_GET['debug']);
    if($this->DEBUG || DEBUG_LEVEL>0){
      $this->o_stats = &Factory::singleton('Es_DB_Stats');
    }
    if(!isset($GLOBALS['MYSQL_CONN'])) $GLOBALS['MYSQL_CONN'] = '';
    else $this->is_1st_obj = false;
  }
   
  function __destruct(){
    // for session_db.php
    if($this->is_1st_obj && !is_resource($GLOBALS['MYSQL_CONN'])) $GLOBALS['MYSQL_CONN'] = $this->CONN;
  }
  
	function error($text = '')	{

		if($this->ERR_EXIT){

		  $v = array();
		  $v['mysql_error'] = mysql_error();
		  $v['mysql_errno'] = mysql_errno();
		  $v['date'] = date('l dS of F Y h:i:s A');
		  $v['ADMIN_EMAIL'] = ADMIN_EMAIL;
		  $v['EC_TITLE'] = EC_TITLE;
      $v['REQUEST_URI'] = html_esc($_SERVER['REQUEST_URI']);
      $v['HTTP_REFERER'] = html_esc($_SERVER['HTTP_REFERER']);
		  EvalAdvTpl(TPL_PATH.'error_db_query.htm',$v,1);
      
      // FileWrite("/path/error_sql_log", $text."\n".$v['mysql_error']."\n".$v['REQUEST_URI']."\n\n", true);
		  // Display Error Details if debug option is enabled only
		  if(EN_DEBUG_SQL==1){ 
        echo $text;
        // print_r(debug_backtrace());
        // debug_print_backtrace(); // php5
      }
		  exit;
		}
		else $this->ERR_MSG = mysql_error();
	}

	function connect($server, $user = '', $pass = '', $dbase = '', $new_link = FALSE) {

		if($user=='' && $pass==''){
		  $user = ini_get('mysql.default_user');
		  $pass = ini_get('mysql.default_password');
    }

    if(!function_exists('mysql_connect')) die('No MySQL extension found');
		$this->CONN = @mysql_connect($server,$user,$pass,$new_link);
		if(!$this->CONN) return false; // since 4.0.5
		if($dbase) $this->set_db($dbase);
    // possible mysql 5.x tweaks
//    mysql_query('SET SQL_MODE="MYSQL40"', $this->CONN);
//    mysql_query('SET SESSION storage_engine=MyISAM', $this->CONN);
		return true;
	}

/*
Valid SQL examples :
$db->query('SELECT * FROM TABLE WHERE COND="'.$db->quote($val).'"');
$db->query('SELECT * FROM TABLE WHERE COND='.$db->esc($val));
$db->query('SELECT * FROM TABLE WHERE COND=?', array($val));
$db->query('SELECT * FROM TABLE WHERE COND=:val', array(':val'=> $val));
*/

  function query($sql, $a_in = NULL) {

	  if($this->DEBUG) $this->o_stats->startQuery();

    $res = NULL;
    if(!is_null($a_in)){

      if(!is_array($a_in)) $a_in = array($a_in);

      if(is_object($this->CONN)){ // PDO
        $res = $this->CONN->prepare($sql);
        $res->execute($a_in);
      }
      elseif(key($a_in)===0){
        $a_sql = explode('?', $sql);
        $sql = '';
        $cnt = count($a_in);
        for($k=0;$k<$cnt;$k++){
          if($a_in[$k]!='') $a_in[$k] = mysql_real_escape_string($a_in[$k],$this->CONN);
          $sql.=$a_sql[$k].'"'.$a_in[$k].'"';
        }
        $sql.=$a_sql[$k];
      }
      else{
        foreach(array_keys($a_in) as $k){
          if($a_in[$k]!='') $a_in[$k] = mysql_real_escape_string($a_in[$k],$this->CONN);
          $sql = str_replace( ($k[0]!=':' ? ':' : '').$k , '"'.$a_in[$k].'"', $sql);
        }
      }
    }
    
    /*if(filesize(SITE_PATH.'_x_trace.log')==0) $GLOBALS['_x_trace'] = 1;
    if($GLOBALS['_x_trace']){
      static $ts;
      if(!isset($ts)) $ts = time();
    }*/

    if(!$res) $res = mysql_query($sql, $this->CONN);

    //if($GLOBALS['_x_trace']) FileWrite(SITE_PATH.'_x_trace.log',(time()-$ts)." - $sql\r\n",1);
    
    if(!$res) $this->error("QUERY failed : $sql");
    if($this->DEBUG || DEBUG_LEVEL>0){ 
      if($this->DEBUG) $this->o_stats->endQuery();
      $this->o_stats->logSQL($sql);
    }
    return $res;
  }

	function insert_id() {
		return (int)mysql_insert_id($this->CONN);
	}

  function affected_rows() {
    return (int)mysql_affected_rows($this->CONN);
  }

  function set_db($name){
    if(!$name || $this->CURDB==$name) return;
	if(!@mysql_select_db($name,$this->CONN)) $this->error('DB select failed');
	$this->CURDB = $name;
  }

  function esc($s) {
    if($s=='') return '""';
    return '"'.mysql_real_escape_string($s,$this->CONN).'"';
  }

  function quote($s) { // deprecated, use esc() instead ?
    if($s=='') return '';
    return mysql_real_escape_string($s,$this->CONN);
  }

  function one_data($sql, $a_in = NULL) { 

/*    if(is_null($a_in) && strpos($sql, TBL_AD)){
      $v = SQL_GetCached($sql);
      if($v!==false) return $v;
    }*/

    $res = $this->query($sql, $a_in);
    if(empty($res)) return;
    $v = mysql_fetch_row($res);
    return $v[0];
  }

	function one_assoc($sql, $a_in = NULL) {
	  $res = $this->query($sql, $a_in);
 	  if(empty($res)) return array();
	  return mysql_fetch_assoc($res);
	}

	function one_row($sql, $a_in = NULL) {
    $res = $this->query($sql, $a_in);
   	if(empty($res)) return array();
    return mysql_fetch_row($res);
	}

  function one_col_array($sql, $a_in = NULL){
 	  $res = $this->query($sql, $a_in);
	  if(empty($res)) return array();
	  $data = array();
    while ($v = mysql_fetch_row($res)) $data[] = $v[0];
    mysql_free_result($res);
	  return $data;
  }

  function two_col_assoc($sql, $a_in = NULL){
 	  $res = $this->query($sql, $a_in);
	  if(empty($res)) return array();
    $data = array();
    while($v = mysql_fetch_row($res))	$data[$v[0]] = $v[1];
    mysql_free_result($res);
	  return $data;
  }

  function select($sql, $a_in = NULL, $mode = 'FETCH_ASSOC'){
		
		$res = $this->query($sql, $a_in);
    if(empty($res)) return array();
		$data = array();

    if($mode == 'FETCH_ORDERED'){
		  while ($v = mysql_fetch_row($res)) $data[] = $v;
    }
    else{
		  while ($v = mysql_fetch_assoc($res)) $data[] = $v;
    }
	  mysql_free_result($res);
		return $data;
  }

  function version() {
    if(defined('DB_VERSION')) return DB_VERSION;
    $s = explode('.', mysql_get_server_info($this->CONN));
    define('DB_VERSION', (int)sprintf('%d%02d%02d', $s[0], $s[1], intval($s[2])));
    return DB_VERSION;
  }

  function get_server_info() { return mysql_get_server_info($this->CONN); }

// some extra functions

	function getAll($sql, $params = NULL){	return $this->select($sql, $params); }

  function getCol($sql, $col = 0, $a_in = NULL){
 	  $res = $this->query($sql, $a_in);
	  if(empty($res)) return array();
	  $data = array();
    if(is_int($col)){
	    while ($v = mysql_fetch_row($res)) $data[] = $v[$col];
    }
    else{
	    while ($v = mysql_fetch_assoc($res)) $data[] = $v[$col];
    }
    mysql_free_result($res);
	  return $data;
  }

  function getAssoc($sql, $force_array = false, $a_in = NULL, $mode = 'FETCH_ORDERED'){
 	  
 	  $res = $this->query($sql, $a_in);
	  if(empty($res)) return array();

    $data = array();

    if(!$force_array && mysql_num_fields($res) == 2){
      while($v = mysql_fetch_row($res))	$data[$v[0]] = $v[1];
    }
    else{
      if($mode != 'FETCH_ORDERED'){ // 'FETCH_ASSOC' or DB_FETCH_ASSOC compat
	      $fid = mysql_field_name($res, 0);
	      while($v = mysql_fetch_assoc($res)){
          $k = $v[$fid];
          unset($v[$fid]);
          $data[$k] = $v;
        }
      }
      else{
	      while($v = mysql_fetch_row($res)){ 
          $k = $v[0];
          unset($v[0]);
          $data[$k] = $v; // array_values ??
        }
      }
    }
    mysql_free_result($res);
	  return $data;
  }

}

/*function SQL_GetCached($sql){
  $sql_up = strtoupper($sql);
  if(strpos($sql_up, 'COUNT(*)')){ //!strncmp($sql_up,'SELECT ',7)
    $key = 'sql_'.md5($sql);
    $cache = &Factory::singleton('Hw_Cache');
    $updated = 0;
    if(!$cache->isExpired($key, $updated)){
      $data = file_get_contents($cache->getFilePath($key));
    }
    else{
      global $db;
      $db->query('LOCK TABLE '.TBL_AD.' WRITE');
 	  $res = $db->query($sql);
      $data = mysql_fetch_row($res);
      $data = $data[0];
      FileWrite($cache->getFilePath($key), $data);
      $db->query('UNLOCK TABLES');
    }
    return $data;
  }
  return false;
}*/
Return current item: Esvon Personals