www.gusucode.com > 同城苏州黄页系统php源码程序 > lib/mysql.class.php

    <?php

class mysql
{
    var $dbhost;
    var $dbuser;
    var $dbpwd;
    var $dbname;
    var $conn;
    var $errmsg;
    var $sql;
    var $debug = false;


    //構造函數
    function mysql($host='', $user="", $pwd="", $db="" ,$pconnect=false)
    {

    }//DBMysql----------

    //debug
    function Debug()
    {
        $this->errmsg = @mysql_error();
        $msg = "<hr><b>SQL String:</b><br>".$this->sql;
        $msg.= "<br>---------------------<br><b>Error Message:</b><br>";
        $msg.= $this->errmsg;
        $msg.= "<hr>";
        echo $msg;
    }//Debug----------

    /*
    執行insert/update等無返回值的操作,函數返回受影響行數
    select操作返回數組形式的值
    $fecth = 0 ,当只有一条记录时,仅返回该记录
    */
    function Query($sql, $fecth = true)
    {
        !empty($sql)?$this->sql=$sql:null;
		if (!$rs = @mysql_query($this->sql))
	    {
			$this->debug?$this->debug():null;
			return false;
	    }


	    if (preg_match("/select.*?from/i", $this->sql))
	    {
			$r=array();
			$record_num=mysql_num_rows($rs);
			//echo "\$record_num:$record_num";exit;
			if( ($record_num==1) && $fecth )
				$r=mysql_fetch_assoc($rs);
			else if($record_num ==0 )
				$r = 0;
			else
			{
				while ($v = mysql_fetch_assoc($rs))
					$r[] = $v;
			}

			mysql_free_result($rs);

			$this->debug?$this->debug():null;
			return $r;
	    }
	    else
	    {
	    	$this->debug?$this->debug():null;
	        return $rs;
        }

    }//query-------

    function _parseFldParameter( &$fields)
    {
    	if( is_array($fields) )
		{
			foreach ($fields as $idx=>$fld)
			{
				if( !strstr($fld,'`') )
					$fields[$idx] = "`$fld`" ;
			}
			$fields=implode(",",$fields);
		}
		else
		{
            $fields = '`'.$fields.'`';
            if (strpos($fields,',')!==false)
                $fields = str_replace(',', '`,`', $fields);
		}
		return $fields = str_replace('`*`', '*', $fields);
    }
    /*
    使用方法:
    $db->select('tableName', 'id,name', 'id>100');
    你要那個標識,最後加個true參數
    */
    function Select($table_or_sql, $condition='1=1', $fields='*',  $fetch=false)
    {
		if( !strstr( $table_or_sql, ' ' ) )
		{
			$this->_parseFldParameter( $fields ) ;
			$sql = "SELECT $fields FROM `$table_or_sql` WHERE $condition";
		}
		else
			$sql = $table_or_sql ;

		return $this->query($sql, $fetch);
    }

    /*
    獲取一行內容,以數組方式返回
	參數SQL一般是取得一行內容的語句
    */
    function GetRow( $table_or_sql='', $where='1', $fields='*' )
    {
    	
    	if( preg_match( "/^select /i", $table_or_sql ) or empty($table_or_sql) )
    	// 传递 sql 参数
    	{
	        !empty($table_or_sql)?$this->sql = $table_or_sql:null;
	        if (!$rs = @mysql_query($this->sql))
	        {
	        	$this->debug?$this->debug():null;
	        	return false;
	        }
	        if (mysql_num_rows($rs)>0)
	        	return mysql_fetch_assoc($rs);
	        else
	        	return false;
    	}
    	else
    	// 
    	{
    		$this->_parseFldParameter( $fields ) ;
    		$this->sql = "Select {$fields} From `$table_or_sql` Where {$where} limit 0,1" ;
    		if( $re = $this->query( $this->sql, false ) )
    			return $re[0] ;
    		else
    			return false ;
    	}
    }//get row------------
    

    /*
    獲取某一行中某一字段的值
    */
    function GetOneField($table, $field, $condition='1=1')
    {
		$sql = "SELECT $field FROM `$table` where $condition";
		if(!$r=mysql_query($sql))
			return false;

		$arr=mysql_fetch_assoc($r);
		return $arr[$field];

	}//getOne---------
    /*
    写入某一行中某一字段的值
    */
    function SetOneField($table, $field, $value, $condition='1=1')
    {
		$sql = "update `$table` set `$field`='$value' where $condition";
		return mysql_query($sql);
	}//getOne---------

    /*
    這個有誤,再改吧
    以有條件方式獲取一行內容,以數組方式返回
	參數SQL一般是取得一行內容的語句
    */
    function GetRowByField($table, $condition='1=1', $fetch=false)
    {
		$this->sql = "SELECT * FROM $table WHERE $condition";

    }

     /*
    向某表中插入數據
    參數說明:
    $data = array('name'=>'eyes','age'=>25);
    */
	function Insert($table, $data, $frompost=true)
	{
        if (count($data)>1)
        {
	        $t1 = $t2 = array();
	        foreach($data as $key=>$value)
	        {
	            $t1[] = $key;
	            if ($frompost)
	            {
	                $value = get_magic_quotes_gpc()?$value:addslashes($value);
	            }
	            else
	            {
	                $value = addslashes($value);
	            }
	            $t2[] = "'".$value."'";
	        }
	        $sql =  "INSERT INTO `$table` (`".implode("`,`",$t1)."`) VALUES(".implode(",",$t2).")";
        }
        else
        {
        	$arr = array_keys($data);
        	$feild = $arr[0];
        	$value = $data[$feild];
            $sql = "INSERT INTO `$table` (`$feild`) VALUES ('$value')";
        }
		$this->debug?$this->debug():null;
		return $this->query($sql);

	}

    /*
    更新數據一條數據
    參數形式:
    $data=array('id'=>1,'name'=>'eyes');
    $conditon = 'id=100';
    */
	function Update($table, $data, $condition, $frompost = true)
	{
		$arr = array();
        foreach ($data as $f=>$v)
        {
            if ($frompost)
            {
				$v = get_magic_quotes_gpc()?$v:addslashes($v);
            }
            else
            {
				$v = addslashes($v);
            }
     		$arr[] = "`$f`='".$v."'";
        }
       
        $sql = "UPDATE `$table` SET ".implode(",", $arr)." WHERE $condition";
		return $this->query($sql);
	}

	function increase( $table, $field, $where, $step = 1 )
	{
		$sql = "UPDATE `{$table}` SET `{$field}`=`{$field}` + {$step} WHERE $where";
		return $this->query($sql);		
	}

	function decrease( $table, $field, $where, $step = 1 )
	{
		$sql = "UPDATE `{$table}` SET `{$field}`=`{$field}` - {$step} WHERE $where";
		return $this->query($sql);		
	}
	
	
	
    /* 
    刪除一條數據
    $field,$id在函數中是如下使用的 where $field=$value
    $data爲一數組格式爲:$data[$fieldName]=$fieldValue
    */
	function Delete($table, $condition)
	{
		$sql = "DELETE FROM `$table` WHERE $condition";
		return $this->Query($sql);
	}

	/*
	返回mysql_insert_id
	*/
	function Id()
	{
		return mysql_insert_id($this->conn);
	}

	/*
    count
    返回符合條件的數據總數
    用法:
    select count(*) from table where id<100 and id<2000
    像上面的SQL語句,應該這樣用:
    count($tableName,'id<100 and id<2000')
    注:$condition條件沒有,就是取出表中的記錄總數
	*/
    function Count($table, $condition='1=1')
    {
		$this->sql = "SELECT count(*) AS c FROM $table where $condition";
		$rs  = @mysql_query($this->sql);
		$row = @mysql_fetch_array($rs);
		$this->debug?$this->debug():null;
		return $row["c"];
    }




}//class end--------




?>