getField($sql); 获取某一字段值
* $db->getRow($sql); 获取某一行数据
* $db->getList($sql); 获取多行数据
* $db->exe($sql); 执行数据库操作:insert update delete....
*/
class MySqlDB
{
private $host = 'localhost';
private $user = 'root';
private $passwd = 'loving';
private $connection = null;
private $db_name = null;
private $resultSet = null;
private $sql = '';
private static $instance = null;
private function __construct($host, $port, $user, $passwd) {
$this->host = $host.($port ? ':'.$port : '');
$this->user = $user;
$this->passwd = $passwd;
$this->connection = mysql_connect($this->host, $this->user, $this->passwd) or die ('can not connect!'.mysql_error());
}
public static function getDB($host, $port, $user, $passwd, $db_name) {
$key = md5($host.'-'.$port.'-'.$user.'-'.$passwd);
if (MySqlDB::$instance == null || MySqlDB::$instance[$key] == null){
MySqlDB::$instance[$key] = new MySqlDB($host, $port, $user, $passwd);
}
MySqlDB::$instance[$key]->db_name = $db_name;
mysql_query("SET NAMES utf8", MySqlDB::$instance[$key]->connection);
mysql_select_db($db_name, MySqlDB::$instance[$key]->connection);
return MySqlDB::$instance[$key];
}
protected function _query($sql) {
$this->sql = $sql;
$this->resultSet = mysql_query($this->sql, $this->connection);
return mysql_num_rows($this->resultSet);
}
/**
* 执行SQL语句
* @param string $sql SQL指令
* @return false | integer
*/
public function exe($sql) {
$this->sql = $sql;
$this->resultSet = mysql_query($this->sql, $this->connection);
return mysql_affected_rows();
}
/**
* 查询某一字段
* @param string $sql 查询语句
* @param string $is_array 返回结果集是否是数组
* @return mixed
*/
public function getField($sql, $is_array = false) {
$result = $this->_query($sql);
if ($result === false){
return false;
}
if( false == $is_array ){
$res = mysql_fetch_array($this->resultSet, MYSQL_NUM);
return $res[0];
}else{
while ( $row = mysql_fetch_array($this->resultSet, MYSQL_ASSOC) ){
$res[] = $row[0];
}
return $res;
}
}
/**
* 获取当行数据
* @param string $sql 查询语句
* @return mixed
*/
public function getRow($sql) {
$result = $this->_query($sql);
if ($result === false){
return false;
}
return mysql_fetch_array($this->resultSet, MYSQL_ASSOC);
}
/**
* 获取多行数据
* @param string $sql 查询语句
* @param string $key 字段名称,false: 返回索引数组; field_name: 返回键值数组
* @param string $value 字段名称,false: 返回键值多维数组;field_name: 返回键值二位数组
* @return mixed
*/
public function getList($sql, $key = false, $value = false) {
$result = $this->_query($sql);
if ($result === false){
return false;
}
if( false == $key ){
while ( $row = mysql_fetch_array($this->resultSet, MYSQL_ASSOC) ){
$res[] = $row;
}
}elseif( false == $value ){
while ( $row = mysql_fetch_array($this->resultSet, MYSQL_ASSOC) ){
$res[$row[$key]] = $row;
}
}else{
while ( $row = mysql_fetch_array($this->resultSet, MYSQL_ASSOC) ){
$res[$row[$key]] = $row[$value];
}
}
return $res;
}
public function __destruct() {
mysql_close($this->connection);
MySqlDB::$instance = null;
}
}
?>
MySql数据库操作类
最新推荐文章于 2021-02-28 12:57:44 发布