<?php
class DB_MySQL
{
/*
加载数据库配置
1 服务器地址 2用户名 3密码 4库名
*/
public function __construct($servername,$dbusername,$dbpassword,$dbname)
{
$this->mysqli = new mysqli($servername, $dbusername, $dbpassword, $dbname);
if ( mysqli_connect_errno() ) die(mysqli_connect_error());
}
public function query($sql)
{return $this->mysqli->query($sql);}
/*取出刚存入的ID 返回id值 该表必须id自动递增的格式*/
public function insert_id()
{return $this->mysqli->insert_id;}
public function affected_rows($sql)
{
$this->query($sql);
return $this->mysqli->affected_rows;
}
/*
mysqli_fetch_array返回循环数组方式 mysqli_fetch_array()这个函数需要内容才能输出,如果sql语句出错了,就没有内容了,就警告了
*/
public function fetch_array($query)
{return mysqli_fetch_array($query);}
/*单数据sql*/
public function fetch_one_array($query)
{return $this->fetch_array($this->query($query));}
/*统计 返回数字*/
public function fetch_one($query)
{
$record = $this->fetch_one_array($query);
Return $record[0];
}
/*清除 退出数据连接*/
public function close()
{return $this->mysqli->close();}
/*新增字段数字转换*/
private function compile_db_insert_string($data)
{
$field_names = "";
$field_values = "";
foreach ($data as $k => $v)
{
$field_names .= "$k,";
$field_values .= "'$v',";
}
$field_names = preg_replace( "/,$/" , "" , $field_names );
$field_values = preg_replace( "/,$/" , "" , $field_values );
return array('FIELD_NAMES' => $field_names, 'FIELD_VALUES' => $field_values);
}
/*修改字段数字转换*/
private function compile_db_update_string($data)
{
$return_string = "";
foreach ($data as $k => $v)
{
if(is_array($v))
{$return_string .= $k . "=".$v['0'].",";}
else
{$return_string .= $k . "='".$v."',";}
}
return preg_replace( "/,$/" , "" , $return_string );
}
/*新增*/
public function insert_sql( $tbl , $arr ,$action="INSERT")
{
$dba = $this->compile_db_insert_string( $arr );
$sql = "{$action} INTO {$tbl} ({$dba['FIELD_NAMES']}) VALUES ({$dba['FIELD_VALUES']})";
return $sql;
}
/*修改*/
public function update_sql($tbl,$arr,$where='')
{
$dba = $this->compile_db_update_string( $arr );
$query = "UPDATE {$tbl} SET $dba";
if ( $where ) $query .= " WHERE ".$where;
return $query;
}
}
?>
|