数据库工具类,单例,完成数据库连接,提供3种数据查询方式。
<?php
class SqlTool{
public $link=null;
private $host;
private $user;
private $psw;
private $charset;
private $db;
private function __construct($load_arr){
$this->host=!empty($load_arr['host']) ? $load_arr['host']:"localhost";
$this->user=!empty($load_arr['user']) ? $load_arr['user']:"root";
$this->psw=!empty($load_arr['psw']) ? $load_arr['psw']:die("密码错误");
$this->charset=!empty($load_arr['charset']) ? $load_arr['charset']:"utf8";
$this->db=!empty($load_arr['db']) ? $load_arr['db']:"db23";
$this->link=@mysql_connect("$this->host","$this->user","$this->psw") or die('链接失败,sorry');
mysql_query("set names $this->charset");
mysql_query("use $this->db");
}
private static $instance = null;
static function GetInstance($load_arr){
if(!(self::$instance instanceof self)){
self::$instance = new self($load_arr);
}
return self::$instance;
}
private function __clone(){}
function Close(){
mysql_close($this->link);
}
//最常用的语句函数 query
function Query($str){
$result = mysql_query($str);
if($result==false){
echo "<p>错误代码".mysql_errno();
echo "<p>错误".mysql_error();
echo "<p>错误语句".$str;
die("<p>byebye!");
}
return $result;
}
//查多行数据
function GetRows($str){
$result=$this->Query($str);
$arr=array();
while($rec=mysql_fetch_assoc($result)){
$arr[]=$rec;
}
mysql_free_result($result);
return $arr;
}
//查单行数据
function GetOneRow($str){
$result=$this->Query($str);
$arr=mysql_fetch_assoc($result);
mysql_free_result($result);
return $arr;
}
//查单个数据
function GetSingle($str){
$result=$this->Query($str);
$arr=mysql_fetch_row($result);
mysql_free_result($result);
return $arr[0];
}
}
?>