<?php
class db { 
	var $pconnect = FALSE;
	var $dbhost;
	var $dbname;
	var $dbuser;
	var $dbpw;
	var $dbconn;
	var $dbcoding;
	var $result;
	var $num_rows;
	var $insert_id;
	//var $affected_rows;//
	public function __construct($host, $user, $pw, $name, $coding){ 
		$this->dbhost = $host; 
		$this->dbuser = $user; 
		$this->dbpw = $pw; 
		$this->dbname = $name;
		$this->dbcoding = $coding;
		$this->connect();
	}
  	//
	public function connect()
	{
		if ($this->pconnect) {
			$this->dbconn = mysql_pconnect($this->dbhost,$this->dbuser,$this->dbpw);
		}
		else {
			$this->dbconn = mysql_connect($this->dbhost,$this->dbuser,$this->dbpw);
		}
		//mysql_select_db($this->dbname, $this->dbconn);
		//mysql_query("SET NAMES $this->dbcoding");
		if (!$this->dbconn) echo "数据库连接失败...数据库ip，用户名，密码对吗？"; 
		if (!mysql_select_db($this->dbname, $this->dbconn)) echo "数据库选择失败...数据库名对吗？";
		$this->query("SET NAMES $this->dbcoding");
	}
  	//
  	public function query($sql)
  	{
  		//echo $sql;
		return $this->result = mysql_query($sql, $this->dbconn);
  	}
  	//
	public function fetch_assoc($result = null)
	{
  		return mysql_fetch_assoc($result); 
  	}
  	//
  	public function fetch_row($result = null)
  	{
  		return mysql_fetch_row($result); 
  	}
  	//
  	function num_rows($result = null)
  	{
  		return mysql_num_rows($result); 
  	}
	function insert_id()
	{
		return mysql_insert_id();
	}
	/* ====================== 原始mysql处理函数 ====================== */
	function insert($sql)
	{
		$this->query($sql);
		return mysql_affected_rows() > 0 ? mysql_affected_rows() : 0;
	}
	function delete($sql)
	{
		$this->query($sql);
		if ($this->result == true) {
			return mysql_affected_rows() == 0 ? 1 : mysql_affected_rows();
		}
		return 0;
	}
	function update($sql)
	{
		$this->query($sql);
		if ($this->result == true) {
			return mysql_affected_rows() == 0 ? 1 : mysql_affected_rows();
		}
		return 0;		
	}
	function select($sql)
	{
		$result = $this->query($sql);
		$rows = array();
		while ($row = $this->fetch_assoc($result)) $rows[] = $row;
		return $rows;
	}
	function select_one($sql)
	{
		$result = $this->query($sql);
		$row = array();
		return $row = $this->fetch_assoc($result);
	}
	//可以用于判断符合sql条件的总行数(但sql必须遵循 "select count(id) from table where条件")合适，也可以用户判断某行是否存在
	function count($sql)
	{
		$result = $this->query($sql);
		$rows = $this->fetch_row($result);
		if (is_array($rows)) return $rows[0];
		return 0;
	}
}
?>
