php连接数据库的类
原创
52cxy
06-03 16:41
阅读数:2846
分享一个php连接数据的工具类:
<?php
/* 数据库管理工具类 */
class dbutil {
var $link;
function connect($dbhost, $dbuser, $dbpw, $dbname = '', $dbcharset = '', $pconnect = 0) {
mysqli_report(MYSQLI_REPORT_OFF);
$this->link = new mysqli();
if(!$this->link->real_connect($dbhost, $dbuser, $dbpw, $dbname, null, null, MYSQLI_CLIENT_COMPRESS)) {
$this->halt('Can not connect to MySQL server');
}
if($dbcharset) {
$this->link->set_charset($dbcharset);
}
$this->link->query("SET sql_mode=''");
$this->link->query("SET character_set_client=binary");
}
function fetch_array($query, $result_type = MYSQLI_ASSOC) {
return $query ? $query->fetch_array($result_type) : null;
}
function result_first($sql) {
$query = $this->query($sql);
return $this->result($query, 0);
}
function fetch_first($sql) {
$query = $this->query($sql);
return $this->fetch_array($query);
}
function fetch_all($sql) {
$arr = array();
$query = $this->query($sql);
while($data = $this->fetch_array($query)) {
$arr[] = $data;
}
return $arr;
}
function query($sql, $type = '') {
$resultmode = $type == 'UNBUFFERED' ? MYSQLI_USE_RESULT : MYSQLI_STORE_RESULT;
if(!($query = $this->link->query($sql, $resultmode)) && $type != 'SILENT') {
$this->halt('MySQL Query Error', $sql);
}
return $query;
}
function affected_rows() {
return $this->link->affected_rows;
}
function error() {
return $this->link->error;
}
function errno() {
return $this->link->errno;
}
function result($query, $row) {
if(!$query || $query->num_rows == 0) {
return null;
}
$query->data_seek($row);
$assocs = $query->fetch_row();
return $assocs[0];
}
function num_rows($query) {
$query = $query ? $query->num_rows : 0;
return $query;
}
function num_fields($query) {
return $query ? $query->field_count : 0;
}
function free_result($query) {
return $query ? $query->free() : false;
}
function insert_id() {
return ($id = $this->link->insert_id) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);
}
function fetch_row($query) {
$query = $query ? $query->fetch_row() : null;
return $query;
}
function fetch_fields($query) {
return $query ? $query->fetch_field() : null;
}
function version() {
return $this->link->server_info;
}
function escape_string($str) {
return $this->link->escape_string($str);
}
function close() {
return $this->link->close();
}
function halt($message = '', $sql = '') {
api_msg('run_sql_error', $message.'<br /><br />'.$sql.'<br /> '.$this->link->error());
}
}
相关代码下载:
共0条评论