PHP之封装MySQL类

config.inc.php内容如下

<?php
return array(
    'DB_HOST' => '192.168.188.134',
    'DB_NAME' => 'scoreboard', 
    'DB_USER' => 'score',
    'DB_PASS' => '123456',
    'DB_CHARSET' => 'utf8',
    'IS_LOG' => 1,//开启日志
    'LOGFILEPATH' => '../log.txt'//日志路径
);
/*
    $database = require('./config.php');
    echo $database['DB_TYPE'];   //输出'DB_TYPE'
*/

?>

表设计如下

create database scoreboard;
use scoreboard;

create table users(
id int not null auto_increment primary key,
gid int not null,                --组id
username varchar(20) not null,
password varchar(32) not null,
sex varchar(2) not null,
totalscore int  --个人总积分
);

create table share(
id int not null auto_increment primary key,
uid int not null,
content varchar(1024) not null,  --分享内容
comment varchar(1024) not null,   --点评
date varchar(15) not null       --分享日期
);

create table score(
id int not null auto_increment primary key,
uid int not null,               --用户id
score int not null,             --用户单次积分
);

grant all privileges on scoreboard.* to 'score'@'%' identified by '123456';
flush privileges;

封装类如下

<?php

class mysql {
    private $logfilepath;
    private $is_log;
    private $hlog;
    private $conn;

    //构造函数
    public function __construct()
    {
        $config = include_once(dirname(__FILE__)."/../config/config.inc.php");
        $this->is_log = $config['IS_LOG'];
        $this->logfilepath = $config['LOGFILEPATH'];

        if ($this->is_log){
            $handle = fopen($this->logfilepath,"a+");
            $this->hlog = $handle;
        }

        $this->conn = $this->connect($config['DB_HOST'],$config['DB_USER'],$config['DB_PASS'],$config['DB_NAME'],$config['DB_CHARSET']);
    }

    //连接数据库
    public function connect($dbhost, $dbuser, $dbpass, $dbname, $dbcharset)
    {
        $this->conn = @mysql_connect($dbhost,$dbuser,$dbpass);
        if (!$this->conn) {
            $msg = "连接数据库失败:".mysql_error();
            $this->write_log($msg);
            die($msg);
        } else {
            if (!@mysql_select_db($dbname)) {
                $msg = "连接数据库成功,但选择数据库失败:".mysql_error();
                $this->write_log($msg);
                die($msg);
            } else {
                $msg = "连接数据库成功,且选择数据库成功";
                $this->write_log($msg);
            }
        }

        @mysql_query("set names ".$dbcharset);

    }

    //执行语句
    public function query($sql){
        
        $result = @mysql_query($sql);

        if (!$result) {
            $this->write_log('mysql_query error:'.mysql_error());
        } else {
            $this->write_log('执行语句:'.$sql.' 且执行成功');
        }
        return $result;
    }

    //查询一条数据
    public function select_one($tab,$column = "*",$condition = '',$debug=False)   //查询函数
    {
        $condition = $condition ? ' where ' . $condition : NULL;
        $sql = "select $column from $tab $condition ";
        if ($debug) {
            echo '将执行语句:'.$sql.'<br />';
        } else {
            $result = $this->query($sql);
            $row = @mysql_fetch_assoc($result);
            return $row;
        }
    }

    //查询多条数据
    public function select_more($tab,$column = "*",$condition = '',$debug=False)   //查询函数
    {
        $condition = $condition ? ' where ' . $condition : NULL;
        $sql = "select $column from $tab $condition";
        if ($debug) {
            echo '将执行语句:'.$sql;
        } else {
            $result = $this->query($sql);
            $i = 0;
            $rows = array();
            while ($row = @mysql_fetch_assoc($result)) {
                $rows[$i] = $row;
                // print_r($rows[$i]);
                $i++; 
            }
            return $rows;
        }
    }

    //返回结果集
    public function echo_result($tab,$column = "*",$condition = '',$debug=False)   //查询函数
    {
        $condition = $condition ? ' where ' . $condition : NULL;
        $sql = "select $column from $tab $condition ";
        if ($debug) {
            echo '将执行语句:'.$sql.'<br />';
        } else {
            return $this->query($sql);
        }
    }

    //插入数据
    public function insert($tab,$arr,$debug=False)
    {
        $value = '';
        $column = '';
        foreach ($arr as $k => $v) {
            $column .= ",{$k}";
            $value .= ",'{$v}'";
        }
        $column = substr($column, 1);
        $value = substr($value, 1);

        $sql = "insert into $tab($column) values($value)";
        if ($debug) {
            echo '将执行语句:'.$sql;
        } else {
            $this->query($sql);
            $num = $this->affected_num();
            $this->write_log("受影响行数:".$num);
            return $num;    //返回受影响行数
        }
    }

    //获取最后插入的id
    public function insert_id() {
        $id = mysql_insert_id($this->link_id);
        $this->write_log('最后插入的id为:'.$id);
        return $id;
    }

    //更新数据
    public function update($tab,$arr,$condition = '',$debug=False)
    {
        if (!$condition) {
            die("error".mysql_error());
        } else {
            $condition = 'where ' . $condition;
        }
        
        $value = '';
        foreach ($arr as $k => $v) {
            $value .= "{$k}='{$v}',";
        }
        $value = substr($value,0,-1);

        $sql = "update $tab set $value $condition";
        if ($debug) {
            echo '将执行语句:'.$sql;
        } else {
            $this->query($sql);
            $num = $this->affected_num();
            $this->write_log("受影响行数:".$num);

            return $num;            
        }
    }

    //删除数据
    public function delete($tab,$condition='',$debug=False)
    {
        $condition = $condition ? ' where ' . $condition : NULL;
        $sql = "delete from $tab $condition";
        if ($debug) {
            echo '将执行语句:'.$sql;
        } else {
            $this->query($sql);
            $num = $this->affected_num();
            $this->write_log("受影响行数:".$num);
            return $num;    //返回受影响行数
        }
    }

    //返回受影响行数
    public function affected_num()
    {
        $num = @mysql_affected_rows();
        return $num;
    }

    //写入日志
    public function write_log($msg='')
    {
        if ($this->is_log){
            $text = date("Y-m-d H:i:s")." ".$msg."\r\n";
            fwrite($this->hlog,$text);
        }
    }

    //关闭数据库连接
    public function close()
    {  
        mysql_close($this->conn);
    }

    //析构函数
    public function __destruct()
    {
        if($this->is_log){
            fclose($this->hlog);
        }
    }
}


    //$db = new mysql();
    
    // //select_one($tab,$column = "*",$condition = '')
    // $rows = $db->select_more('share','*');
    // print_r($rows[0]);
    // print_r($rows[1]);


    // //insert($tab,$arr)
    // $arr = array();
    // $arr['uid'] = '3';
    // $arr['content'] = 'xss';
    // $arr['comment'] = 'very good';
    // $arr['date'] = '1464082630';
    // $db->insert('share',$arr);


    // //update($tab,$arr,$condition = '')
    // $arr = array();
    // $arr['content'] = 'xssxssxssxssxss';
    // $arr['comment'] = 'goodgoodgoodgood';
    // $condition = 'id > 5';
    // $db->update('share',$arr,$condition);


    //$db->delete("share","id between 10 and 15");


    //$db->close();

?>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,340评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,762评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,329评论 0 329
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,678评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,583评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,995评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,493评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,145评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,293评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,250评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,267评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,973评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,556评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,648评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,873评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,257评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,809评论 2 339

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,258评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,559评论 18 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,531评论 18 399
  • 依着一缕静谧的光阴,携一缕暖阳,伴着清风云淡,看一朵素洁小花的明媚淡雅,赏一叶绿草的枝头崭绿,做一个刚刚好的女子,...
    林芳晨阅读 130评论 1 0
  • 小蜗突然发现自己老了,毕竟已经是90后空巢老人了。 想起十年前的网络社交跟现在的对比,相差得不是一点两点。 十年前...
    WIN分享计划阅读 443评论 0 1