mysql类
class mysql extends db {
private static $ins = NULL;
private $conn = NULL;
private $conf = array();
protected function __construct() {
$this->conf = conf::getIns();
//下面用连接函数,选择数据库函数,设置字符集函数初始化,函数在后面有
$this->connect($this->conf->host,$this->conf->user,$this->conf->pwd);
$this->select_db($this->conf->db);
$this->setChar($this->conf->char);
}
public static function getIns() {
if(!(self::$ins instanceof self)) {
self::$ins = new self();
}
return self::$ins;
}
public function connect($h,$u,$p) {
$this->conn = mysql_connect($h,$u,$p);
if(!$this->conn) {
$err = new Exception('连接失败');
throw $err;
}
}
protected function select_db($db) {
$sql = 'use ' . $db;
$this->query($sql);
}
protected function setChar($char) {
$sql = 'set names ' . $char;
return $this->query($sql);
}
//查询函数
public function query($sql) {
$rs = mysql_query($sql,$this->conn);
//把sql语句写入日志
log::write($sql);
return $rs;
}
//自动拼接sql语句;
public function autoExecute($table,$arr,$mode='insert',$where = ' where 1 limit 1') {
/* insert into tbname (username,passwd,email) values ('',)
把所有的键名用','接起来
implode(',',array_keys($arr));
implode("','",array_values($arr));
*/
if(!is_array($arr)) {
return false;
}
if($mode == 'update') {
$sql = 'update ' . $table .' set ';
foreach($arr as $k=>$v) {
$sql .= $k . "='" . $v ."',";
}
$sql = rtrim($sql,',');
$sql .= $where;
return $this->query($sql);
}
$sql = 'insert into ' . $table . ' (' . implode(',',array_keys($arr)) . ')';
$sql .= ' values (\'';
$sql .= implode("','",array_values($arr));
$sql .= '\')';
return $this->query($sql);
}
//查询所有结果,返回的是数组,需要有一个数组
public function getAll($sql) {
$rs = $this->query($sql);
$list = array();
//mysql_fetch_assos返回的是一行数据,所有……用while循环把取得的每一行数据放入list数组;
while($row = mysql_fetch_assoc($rs)) {
$list[] = $row;
}
return $list;
}
//只取得一行数据,就不需要空数组和循环了
public function getRow($sql) {
$rs = $this->query($sql);
return mysql_fetch_assoc($rs);
}
//取得一个数据,用mysql_fetch_row,如想计算学生的总数,当然是取ID号了,id号只能以$row[0]来取出;
public function getOne($sql) {
$rs = $this->query($sql);
$row = mysql_fetch_row($rs);
return $row[0];
}
// 返回影响行数的函数
public function affected_rows() {
return mysql_affected_rows($this->conn);
}
// 返回最新的auto_increment列的自增长的值
public function insert_id() {
return mysql_insert_id($this->conn);
}
}