自制php操作mysql工具类(DB.class.php)
DB.class.php
复制代码
<?php
class DB{
//主机地址
var $host;
//用户名
var $username;
//密码
var $password;
//数据库名
var $dbname;
//字符集
var $charset;
//数据库连接对象,主要用在mysql_query($sql,$this->con);
private $con;
//外界获取的mysqlDB类操作对象
public static $dao;
//获得mysqlDB类对象(单例)
public static function getInstance($config){
if(!isset(self::$dao)){
self::$dao = new self($config);
}
return self::$dao;
}
//private禁止外部new,减少new带来的开销,并设置默认的配置。
private function __construct($config){
$this->host = isset($config['host'])?$config['host']:'localhost';
$this->port = isset($config['port'])?$config['port']:'3306';
$this->username = isset($config['username'])?$config['username']:'root';
$this->password = isset($config['password'])?$config['password']:'root';
$this->dbname = isset($config['dbname'])?$config['dbname']:'test';
$this->charset = isset($config['charset'])?$config['charset']:'utf8';
//连接数据库
$this->con = $this->connect();
//设置数据库名,默认为test
$this->useDb($this->dbname);
//设置字符集,默认为utf8。
$this->setCharset($this->charset);
}
//禁止外部克隆
private function __clone(){
}
//连接不成功在这个分段找。
//////////////////////////////////////////////////////
//连接数据库
public function connect(){
$con =
mysql_connect("$this->host:$this->port","$this->username","$this->password") or die("连接数据库失败");
return $con;
}
//1.执行增、删、改sql语句
public function exec($sql){
$res = mysql_query($sql,$this->con);
if($res){
// echo "<br/>sql语句:".$sql."<br>";
// var_dump($res);
return true;
//要是增删改有问题可以在这里输出sql调试。
}else{
echo "<br/>sql语句:".$sql;
echo "<br/出错信息>:".mysql_error();
echo "<br/出错代码>:".mysql_errno();
exit;
}
}
//额外设置字符集
public function setCharset($charset){
$sql = "set names '$charset'";
$this->exec($sql) or die("set");
//die();
}
//额外设置数据库
public function useDb($dbname){
$sql = "use $dbname";
$this->exec($sql) or die("use");//or die()函数前面需返回对应的true或false;
}
////////////////////////////////////////////////////////
//查找出错在这个部分找。
//4.将查到的结果集转为单个数据,这里是索引数组的第一个字段。
public function getOne($sql){
$rec = mysql_query($sql,$this->con);
$res = mysql_fetch_row($rec);
if($res){
return $res[0];
}else{
return false;
}
}
//可能修改的函数全部放在上面,以便查找。下方函数基本不会修改。
//编号1~4是高频率使用的函数。
//2.获取一行数据(一维)
public function getRow($sql){
$rec = mysql_query($sql,$this->con);
$res = mysql_fetch_assoc($rec);
if($res){
return $res;
}else{
return false;
}
}
//3.获取所有数据(二维)
public function getAll($sql){
$rec = mysql_query($sql,$this->con);
$arr = array();//定义 一个数组
while($res = mysql_fetch_assoc($rec)){
$arr[] = $res;
}
if($arr){
return $arr;
}else{
return false;
}
}
}
$dao = DB::getInstance(null);
?>
<?php
include_once("DB.class.php");
$sql = "select * from goods where id = 1";
//.获取一行数据(一维)
$res = $dao->getRow($sql); var_dump($res);
//以上的getRow函数只是举例,具体如何使用这个工具,首先要在你的php文件中include这个工具类,即include_once("DB.class.php");
//1.要看你的sql语句查回的数据是一维的,还是二维的,或者单个数据。
//对应的函数是getROW,getAll,getOne。
//2.增删改统一用exec。
//3.数据库的连接配置在构造构造函数中修改。
?>
注意事项:
1.文件DB.class.php建好后。
2.在你需要操作数据库接的文件中include这个文件,上面有示例。
3.使用之前必须把数据库名改成你的数据库名。这个是最重要的,也是最容易忘记的。
复制代码
引用
复制代码
<?php
include_once("DB.class.php");
$sql = "select * from goods where id = 1";
//.获取一行数据(一维)
$res = $dao->getRow($sql); var_dump($res);
//以上的getRow函数只是举例,具体如何使用这个工具,首先要在你的php文件中include这个工具类,即include_once("DB.class.php");
//1.要看你的sql语句查回的数据是一维的,还是二维的,或者单个数据。
//对应的函数是getROW,getAll,getOne。
//2.增删改统一用exec。
//3.数据库的连接配置在构造构造函数中修改。
?>
复制代码
注意事项:
1.文件DB.class.php建好后。
2.在你需要操作数据库接的文件中include这个文件,上面有示例。
3.使用之前必须把数据库名改成你的数据库名。这个是最重要的,也是最容易忘记的。
===
数据库连接类 DB.class.php
复制代码
<?php
/**
* 数据库操作类
*/
class DB {
private $link_id;
private $handle; //日志文件句柄
private $is_log;
private $time;
public function __construct() {
header("Content-type: text/html; charset=utf-8");
$this->time = $this->microtime_float();
require_once 'configs/config.db.php';
$this->connect($db_config["hostname"], $db_config["username"], $db_config["password"], $db_config["database"], $db_config["pconnect"]);
$this->is_log = $db_config["log"];
if($this->is_log){
$this->handle = fopen($db_config["logfilepath"] . "dblog.txt", "a+");
}
}
/**
* 连接数据库
*/
public function connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect = 0, $charset ='utf8') {
if($pconnect == 0){
$this->link_id = mysql_connect($dbhost, $dbuser, $dbpw, true);
if(!$this->link_id){
$this->halt("数据库连接失败");
}
}else{
$this->link_id = mysql_pconnect($dbhost, $dbuser, $dbpw);
if(!$this->link_id){
$this->halt("数据库长连接失败");
}
}
if(!mysql_select_db($dbname, $this->link_id)){
$this->halt("数据库选择失败");
}
mysql_query("set names " . $charset);
}
/**
* 查询
* Enter description here ...
* @param unknown_type $sql
*/
public function query($sql){
$this->write_log("查询 " . $sql);
$query = mysql_query($sql, $this->link_id);
if(!$query){
$this->halt("查询失败 " . $sql);
}
return $query;
}
/**
* 获取一条记录(MYSQL_ASSOC,MYSQL_NUM,MYSQL_BOTH)
* Enter description here ...
* @param $sql
*/
public function get_one($sql, $result_type = MYSQL_ASSOC){
$query = $this->query($sql);
$rt = mysql_fetch_array($query, $result_type);
$this->write_log("获取一条记录 " . $sql);
return $rt;
}
/**
* 获取全部记录
* Enter description here ...
* @param unknown_type $sql
* @param unknown_type $result_type
*/
public function get_all($sql, $is_page = false, $page_num = 10, $result_type = MYSQL_ASSOC){
if(!$is_page){
$query = $this->query($sql);
$i = 0;
$rt = array();
while ($row = mysql_fetch_array($query, $result_type))
{
$rt[$i++] = $row;
}
$this->write_log("获取全部记录(无翻页)" . $sql);
}else{
$rt = $this->page($sql, $page_num, $result_type);
}
return $rt;
}
/**
* 获取全部数据(带翻页)
* Enter description here ...
* @param $sql sql语句
* @param $page_num 每页显示记录条数
*/
public function page($sql, $page_num, $result_type){
session_start();
$query = $this->query($sql);
$all_num = mysql_num_rows($query); //总条数
$page_all_num = ceil($all_num / $page_num); //总页数
$page = empty($_GET['page']) ? 1 : $_GET['page']; //当前页数
$page = (int)$page; //安全强制转换
$limit_str = ($page - 1) * $page_num; //记录起始数
$sql .= " limit $limit_str, $page_num";
$query = $this->query($sql);
$i = 0;
$rt = array();
while ($row = mysql_fetch_array($query, $result_type))
{
$rt[$i++] = $row;
}
$this->write_log("获取翻页记录(带翻页)" . $sql);
$_SESSION["page_all_num"] = $page_all_num;
$_SESSION["next"] = $page >= $page_all_num ? $page_all_num : $page + 1;
$_SESSION["pre"] = $page <= 1 ? 1 : $page - 1;
return $rt;
}
/**
* 插入
* Enter description here ...
* @param unknown_type $table
* @param unknown_type $dataArray
*/
public function insert($table,$dataArray) {
$field = "";
$value = "";
if( !is_array($dataArray) || count($dataArray) <= 0) {
$this->halt('没有要插入的数据');
return false;
}
foreach ($dataArray as $key => $val){
$field .="$key,";
$value .="'$val',";
}
$field = substr( $field,0,-1);
$value = substr( $value,0,-1);
$sql = "insert into $table($field) values($value)";
$this->write_log("插入 ".$sql);
if(!$this->query($sql)) return false;
return true;
}
/**
* 更新
* Enter description here ...
* @param unknown_type $table
* @param unknown_type $dataArray
* @param unknown_type $condition
*/
public function update( $table,$dataArray,$condition="") {
if( !is_array($dataArray) || count($dataArray)<=0) {
$this->halt('没有要更新的数据');
return false;
}
$value = "";
while( list($key,$val) = each($dataArray))
$value .= "$key = '$val',";
$value .= substr( $value,0,-1);
$sql = "update $table set $value where 1=1 and $condition";
$this->write_log("更新 ".$sql);
if(!$this->query($sql)) return false;
return true;
}
/**
* 删除
* Enter description here ...
* @param unknown_type $table
* @param unknown_type $condition
*/
public function delete( $table,$condition="") {
if( empty($condition) ) {
$this->halt('没有设置删除的条件');
return false;
}
$sql = "delete from $table where 1=1 and $condition";
$this->write_log("删除 ".$sql);
if(!$this->query($sql)) return false;
return true;
}
/**
* 返回结果集
* Enter description here ...
* @param unknown_type $query
* @param unknown_type $result_type
*/
public function fetch_array($query, $result_type = MYSQL_ASSOC){
$this->write_log("返回结果集");
return mysql_fetch_array($query, $result_type);
}
/**
* 获取记录条数
* Enter description here ...
* @param unknown_type $results
*/
public function num_rows($results) {
if(!is_bool($results)) {
$num = mysql_num_rows($results);
$this->write_log("获取的记录条数为".$num);
return $num;
} else {
return 0;
}
}
/**
* 获取最后插入的id
* Enter description here ...
*/
public function insert_id() {
$id = mysql_insert_id($this->link_id);
$this->write_log("最后插入的id为".$id);
return $id;
}
/**
* 关闭数据库连接
* Enter description here ...
*/
public function close() {
$this->write_log("已关闭数据库连接");
return @mysql_close($this->link_id);
}
/**
* 错误提示
*/
private function halt($msg = ''){
$msg .= "\r\n" . mysql_error();
$this->write_log($msg);
die($msg);
}
/**
* 写入日志文件
*/
public function write_log($msg = ''){
if($this->is_log){
$text = date("Y-m-d H:i:s") . " " . $msg . "\r\n";
fwrite($this->handle, $text);
}
}
/**
* 获得毫秒数
*/
public function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
/**
* 析构函数
* Enter description here ...
*/
public function __destruct(){
$use_time = ($this->microtime_float()) - ($this->time);
$this->write_log("完成整个查询任务,所用时间为 " . $use_time);
if($this->is_log){
fclose($this->handle);
}
}
}
?>
复制代码
config.db.php配置文件
复制代码
<?php
$db_config = array
(
'hostname' => 'localhost',
'username' => 'root',
'password' => '123456',
'database' => 'child_games',
'charset' => 'utf8',
'pconnect' => 0, //是否使用持久连接(0关/1开)
'log' => 1, //是否开启日志(0关/1开)
'logfilepath' => './' //日志文件目录
);
?>
复制代码