class Db{
private $con;
function __construct($mysql_data){
$this->db_connect($mysql_data);
}
/**
* Connect to database
* @param array $mysql_data Database connection information array('host'=>'Host: port','user'=>'User','pass'=>'Password','dbbase'=>' Database','charset'=>'Character type')
**/
function db_connect($mysql_data){
$host = $mysql_data['host'];
$user = $mysql_data['user'];
$pass = $mysql_data['pass'];
$dbbase = $mysql_data['dbbase'];
$charset= $mysql_data['charset'];
$this->con = @mysql_connect($host,$user,$pass) or die('NO SERVER');
if($this->con){
mysql_select_db($dbbase,$this->con) or die('NO DATABASE:'.$dbbase);
mysql_query('set names '.$charset);
}
}
/**
* Execute sql statement
* @param string $sql The sql to be executed
* @return obj
**/
function query($sql){
return mysql_query($sql,$this->con);
}
/**
* Get a query result
* @param string $sql The sql to be executed
* @return array array('id'=>'1','dd'=>'2');
**/
function fetch_row($sql){
$result = $this->query($sql);
return mysql_fetch_assoc($result);
}
/**
* Get the first field value of a result
* @param string $sql The sql to be executed
* @return string
**/
function fetch_first($sql){
$result = $this->query($sql);
$result = mysql_fetch_array($result);
return $result[0];
}
/**
* Return the result set
* @param string $sql The sql to be executed
* @param string $filed The field that needs to be used as an index
* @return array array(array('id'=>'1','dd'=>'2'),array('id'=>'1','dd'=>'2' ));
**/
function fetch_result($sql,$field = null){
$result = $this->query($sql);
$ret_array = array();
while($rows = mysql_fetch_assoc($result)){
if($field){
$ret_array[$rows[$field]]= $rows;
}else{
$ret_array[]= $rows;
}
}
return $ret_array;
}
/**
* Get the new ID
* @return int
**/
function get_insertid(){
return mysql_insert_id();
}
/**
* Single data table insertion
* @param array $Data array('Field 1'=>'Value','Field 2'=>'Value',)
* @param string $table table name
**/
function insert($Data,$table){
//insert into table (字段,字段) values(值,值)
$key_array = implode(',',array_keys($Data));
$key_val = '''.implode('','',array_values($Data)).''';
$sql = "insert into ".$table." ($key_array) values($key_val)";
return $this->query($sql);
}
/**
* Update single table
* @param array $Data array('Field 1'=>'Value','Field 2'=>'Value',)
* @param array $where array('Field 1'=>'Value','Field 2'=>'Value',)Conditions that need to be updated
* @param string $table table name www.2cto.com
**/
function update($Data,$table,$where){
//update table set 字段=值,字段=值 where key =value;
$key_var = array();
foreach($Data as $key=>$val){
$key_var[] = $key."='".$val."'";
}
$key_var = implode(',',$key_var);
$whe_var = array();
foreach($where as $key=>$val){
$whe_var[] = $key."='".$val."'";
}
$whe_var = implode(' and ',$whe_var);
if($whe_var){
$whe_var = ' where '.$whe_var;
}
$sql = "update ".$table." set ".$key_var.$whe_var;
return $this->query($sql);
//return $sql;
}
}