<?php
$mysqlHost = "localhost"; //你的MySQL主机
$mysqlUser = "user"; //你的MySQL帐户
$mysqlPass = "password"; //你的MySQL密码
class Common{
private $link=null;
//构造函数,连接数据库并选择
public function __construct($dbName){
$this->link = mysqli_connect($mysqlHost,$mysqlUser,$mysqlPass);
mysqli_select_db($this->link,$dbName);
}
//构造函数,关闭连接
public function __destruct(){
mysqli_close($this->link);
}
/*
删除表中数据
string $tableName 表名
string $condition 条件
*/
public function delete($tableName,$condition){
$sql = "delete from $tableName $condition";
return $this->query($sql);
}
// 插入数据
// string $tableName 表名
// array $data 数组 增加的数据
public function insert($tableName,$data){
//获取所有的键
$allKey = array_keys($data);
//数组转字符串
$keys = implode(',',$allKey);
//获取所有值
$allValue = array_values($data);
//数组转字符串
$values = implode("','",$allValue);
$values = "'$values'";
$sql = "insert into $tableName ($keys) value ($values)";
return $this->query($sql);
}
//执行SQL语句
private function query($sql){
mysqli_query($this->link,$sql);
if(mysqli_affected_rows($this->link)>0){
return true;
}
return false;
}
//更改表的内容
// string $tableName 表名
// array $data 修改的信息
// string $condition 条件
function updata($tableName,$data,$condition){
$dataStr = "";
foreach($data as $key=>$value){
$dataStr .= "$key='$value',";
}
//把末尾的逗号去掉
$dataStr[strlen($dataStr)-1] = ' ';
$sql = "update $tableName set $dataStr $condition";
return $this->query($sql);
}
//查询表中数据
// string $tableName 表名
// string or array $cols 列名
// string $condition 条件
function select($tableName,$cols,$condition){
if(is_array($cols)){
$cols = implode(',',$cols);
}
$sql = "select $cols from $tableName $condition";
$result = mysqli_query($this->link,$sql);
$resultArr = array();
//取出结果的每一行
while($arr = mysqli_fetch_assoc($result)){
$resultArr = $arr;
}
return $resultArr;
}
}
//$com = new Common('bar');
//$result = $com->select('bar_value','*',"where device='ab'");
//$result = $com->updata('bar_value',array('device'=>'zige','percentage'=>'100'),"where device='abc'");
//$result = $com->insert('bar_value',array('device'=>'abc','percentage'=>'1000'));
//$result = $com->delete('bar_value','where id=1');
//var_dump($result);
?>