﻿<?php
/////////////////////////////////////////////////////////////////////////////
//
// SpeedPHP - 蹇€熺殑涓枃PHP妗嗘灦
//
// Copyright (c) 2008 - 2009 SpeedPHP.com All rights reserved.
//
// 璁稿彲鍗忚璇锋煡鐪?http://www.speedphp.com/
//
/////////////////////////////////////////////////////////////////////////////

/**
 * mysql MySQL鏁版嵁搴撶殑椹卞姩鏀寔 
 */
class mysql {
	/**
	 * 鏁版嵁搴挞摼鎺ュ彞镆?
	 */
	private $conn;
	/**
	 * 镓ц镄凷QL璇彞璁板綍
	 */
	public $arrSql;

	/**
	 * 鎸塖QL璇彞銮峰彇璁板綍缁撴灉锛岃繑锲炴暟缁?
	 * 
	 * @param sql  镓ц镄凷QL璇彞
	 */
	public function getArray($sql)
	{
		if( ! $result = $this->exec($sql) )return FALSE;
		if( ! mysql_num_rows($result) )return FALSE;
		$rows = array();
		while($rows[] = mysql_fetch_array($result,MYSQL_ASSOC)){}
		mysql_free_result($result);
		$this->arrSql[] = $sql;
		array_pop($rows);
		return $rows;
	}
	
	/**
	 * 杩斿洖涓嬩竴涓彃鍏ョ殑涓婚敭ID
	 */
	public function newinsertid()
	{
		return mysql_insert_id($this->conn);
	}

	/**
	 * 镓ц涓€涓猄QL璇彞
	 * 
	 * @param sql 闇€瑕佹墽琛岀殑SQL璇彞
	 */
	public function exec($sql)
	{
		$this->arrSql[] = $sql;
		if( $result = mysql_query($sql, $this->conn) ){
			return $result;
		}else{
			spError("{$sql}<br />镓ц阌栾: " . mysql_error());
		}
	}

	/**
	 * 銮峰彇鏁版嵁琛ㄧ粨鏋?
	 *
	 * @param tbl_name  琛ㄥ悕绉?
	 */
	public function getTable($tbl_name)
	{
		return $this->getArray("DESCRIBE {$tbl_name}", $this->conn);
	}

	/**
	 * 鏋勯€犲嚱鏁?
	 *
	 * @param dbConfig  鏁版嵁搴挞厤缃?
	 */
	public function __construct($dbConfig)
	{
		$this->conn = mysql_connect($dbConfig['host'].":".$dbConfig['port'], $dbConfig['login'], $dbConfig['password']) or spError("鏁版嵁搴挞摼鎺ラ敊璇?: " . mysql_error()); 
		mysql_select_db($dbConfig['database'], $this->conn) or spError("镞犳硶镓惧埌鏁版嵁搴掳紝璇风‘璁ゆ暟鎹簱鍚岖О姝ｇ‘锛?);
		$this->exec("SET NAMES UTF8");
	}
	/**
	 * 瀵圭壒娈婂瓧绗﹁繘琛岃绷婊?
	 *
	 * @param value  链?
	 */
	public function __val_escape($value) {
		if(is_null($value))return 'NULL';
		if(is_bool($value))return $value ? 1 : 0;
		if(is_int($value))return (int)$value;
		if(is_float($value))return (float)$value;
		if(@get_magic_quotes_gpc())$value = stripslashes($value);
		return mysql_real_escape_string($value, $this->conn);
	}

	/**
	 * 鏋愭瀯鍑芥暟
	 */
	public function __destruct()
	{
		@mysql_close($this->conn);
	}
}

