简单的php数据库操作类代码(增,删,改,查)


Posted in PHP onApril 08, 2013

数据库操纵基本流程为:

1、连接数据库服务器

2、选择数据库

3、执行SQL语句

4、处理结果集

5、打印操作信息

其中用到的相关函数有

•resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]] )

连接数据库服务器
•resource mysql_pconnect ( [string server [, string username [, string password [, int client_flags]]]] )

连接数据库服务器,长连接
•int mysql_affected_rows ( [resource link_identifier] )取得最近一次与 link_identifier 关联的 INSERT,UPDATE 或 DELETE 查询所影响的记录行数。
•bool mysql_close ( [resource link_identifier] )如果成功则返回 TRUE,失败则返回 FALSE。
•int mysql_errno ( [resource link_identifier] )返回上一个 MySQL 函数的错误号码,如果没有出错则返回 0(零)。
•string mysql_error ( [resource link_identifier] )返回上一个 MySQL 函数的错误文本,如果没有出错则返回 ''(空字符串)。如果没有指定连接资源号,则使用上一个成功打开的连接从 MySQL 服务器提取错误信息。
•array mysql_fetch_array ( resource result [, int result_type] )返回根据从结果集取得的行生成的数组,如果没有更多行则返回 FALSE。
•bool mysql_free_result ( resource result )释放所有与结果标识符 result 所关联的内存。
•int mysql_num_fields ( resource result )返回结果集中字段的数目。
•int mysql_num_rows ( resource result )返回结果集中行的数目。此命令仅对 SELECT 语句有效。要取得被 INSERT,UPDATE 或者 DELETE 查询所影响到的行的数目,用 mysql_affected_rows()。
•resource mysql_query ( string query [, resource link_identifier] ) 向与指定的连接标识符关联的服务器中的当前活动数据库发送一条查询。如果没有指定 link_identifier,则使用上一个打开的连接。如果没有打开的连接,本函数会尝试无参数调用 mysql_connect() 函数来建立一个连接并使用之。查询结果会被缓存
代码如下:

class mysql {     private $db_host;       //数据库主机
     private $db_user;       //数据库登陆名
     private $db_pwd;        //数据库登陆密码
     private $db_name;       //数据库名
     private $db_charset;    //数据库字符编码
     private $db_pconn;      //长连接标识位
     private $debug;         //调试开启
     private $conn;          //数据库连接标识
     private $msg = "";      //数据库操纵信息
 //    private $sql = "";      //待执行的SQL语句
     public function __construct($db_host, $db_user, $db_pwd, $db_name, $db_chaeset = 'utf8', $db_pconn = false, $debug = false) {
         $this->db_host = $db_host;
         $this->db_user = $db_user;
         $this->db_pwd = $db_pwd;
         $this->db_name = $db_name;
         $this->db_charset = $db_chaeset;
         $this->db_pconn = $db_pconn;
         $this->result = '';
         $this->debug = $debug;
         $this->initConnect();
     }
     public function initConnect() {
         if ($this->db_pconn) {
             $this->conn = @mysql_pconnect($this->db_host, $this->db_user, $this->db_pwd);
         } else {
             $this->conn = @mysql_connect($this->db_host, $this->db_user, $this->db_pwd);
         }
         if ($this->conn) {
             $this->query("SET NAMES " . $this->db_charset);
         } else {
             $this->msg = "数据库连接出错,错误编号:" . mysql_errno() . "错误原因:" . mysql_error();
         }
         $this->selectDb($this->db_name);
     }
     public function selectDb($dbname) {
         if ($dbname == "") {
             $this->db_name = $dbname;
         }
         if (!mysql_select_db($this->db_name, $this->conn)) {
             $this->msg = "数据库不可用";
         }
     }
     public function query($sql, $debug = false) {
         if (!$debug) {
             $this->result = @mysql_query($sql, $this->conn);
         } else {
         }
         if ($this->result == false) {
             $this->msg = "sql执行出错,错误编号:" . mysql_errno() . "错误原因:" . mysql_error();
         }
 //        var_dump($this->result);
     }
     public function select($tableName, $columnName = "*", $where = "") {
         $sql = "SELECT " . $columnName . " FROM " . $tableName;
         $sql .= $where ? " WHERE " . $where : null;
         $this->query($sql);
     }
     public function findAll($tableName) {
         $sql = "SELECT * FROM $tableName";
         $this->query($sql);
     }
     public function insert($tableName, $column = array()) {
         $columnName = "";
         $columnValue = "";
         foreach ($column as $key => $value) {
             $columnName .= $key . ",";
             $columnValue .= "'" . $value . "',";
         }
         $columnName = substr($columnName, 0, strlen($columnName) - 1);
         $columnValue = substr($columnValue, 0, strlen($columnValue) - 1);
         $sql = "INSERT INTO $tableName($columnName) VALUES($columnValue)";
         $this->query($sql);
         if($this->result){
             $this->msg = "数据插入成功。新插入的id为:" . mysql_insert_id($this->conn);
         }
     }
     public function update($tableName, $column = array(), $where = "") {
         $updateValue = "";
         foreach ($column as $key => $value) {
             $updateValue .= $key . "='" . $value . "',";
         }
         $updateValue = substr($updateValue, 0, strlen($updateValue) - 1);
         $sql = "UPDATE $tableName SET $updateValue";
         $sql .= $where ? " WHERE $where" : null;
         $this->query($sql);
         if($this->result){
             $this->msg = "数据更新成功。受影响行数:" . mysql_affected_rows($this->conn);
         }
     }
     public function delete($tableName, $where = ""){
         $sql = "DELETE FROM $tableName";
         $sql .= $where ? " WHERE $where" : null;
         $this->query($sql);
         if($this->result){
             $this->msg = "数据删除成功。受影响行数:" . mysql_affected_rows($this->conn);
         }
     }
     public function fetchArray($result_type = MYSQL_BOTH){
         $resultArray = array();
         $i = 0;
         while($result = mysql_fetch_array($this->result, $result_type)){
             $resultArray[$i] = $result;
             $i++;
         }
         return $resultArray;
     }
 //    public function fetchObject(){
 //        return mysql_fetch_object($this->result);
 //    }
     public function printMessage(){
         return $this->msg;
     }
     public function freeResult(){
         @mysql_free_result($this->result);
     }
     public function __destruct() {
         if(!empty($this->result)){
             $this->freeResult();
         }
         mysql_close($this->conn);
     }
 }

调用代码如下

require_once 'mysql_V1.class.php';
 require_once 'commonFun.php';
 $db = new mysql('localhost', 'root', '', "test"); //select    查
 $db->select("user", "*", "username = 'system'");
 $result = $db->fetchArray(MYSQL_ASSOC);
 print_r($result);
 dump($db->printMessage());
 //insert    增
 //$userInfo = array('username'=>'system', 'password' => md5("system"));
 //$db->insert("user", $userInfo);
 //dump($db->printMessage());
 //update    改
 //$userInfo = array('password' => md5("123456"));
 //$db->update("user", $userInfo, "id = 2");
 //dump($db->printMessage());
 //delete    删
 //$db->delete("user", "id = 1");
 //dump($db->printMessage());
 //findAll   查询全部
 $db->findAll("user");
 $result = $db->fetchArray();
 dump($result);

ps,个人比较喜欢tp的dump函数,所以在commonFun.php文件中拷贝了友好打印函数。使用时将其改为print_r()即可。

PHP 相关文章推荐
使用php来实现网络服务
Sep 15 PHP
mysql From_unixtime及UNIX_TIMESTAMP及DATE_FORMAT日期函数
Mar 21 PHP
php读取javascript设置的cookies的代码
Apr 12 PHP
PHP JS Ip地址及域名格式检测代码
Sep 27 PHP
php多种形式发送邮件(mail qmail邮件系统 phpmailer类)
Jan 22 PHP
将酷狗krc歌词解析并转换为lrc歌词php源码
Jun 20 PHP
PHP类中的魔术方法(Magic Method)简明总结
Jul 08 PHP
php将图片保存入mysql数据库失败的解决方法
Dec 27 PHP
PHP也能干大事之PHP中的编码解码详解
Apr 20 PHP
PHP 进度条函数的简单实例
Sep 19 PHP
php使用redis的有序集合zset实现延迟队列应用示例
Feb 20 PHP
详细分析PHP7与PHP5区别
Jun 26 PHP
PHP If Else(elsefi) 语句
Apr 07 #PHP
PHP插入排序实现代码
Apr 04 #PHP
php 无法加载mcrypt.dll的解决办法
Apr 03 #PHP
PHP常用的文件操作函数经典收藏
Apr 02 #PHP
精美漂亮的php分页类代码
Apr 02 #PHP
php更新mysql后获取影响的行数发生异常解决方法
Mar 28 #PHP
php页面跳转代码 输入网址跳转到你定义的页面
Mar 28 #PHP
You might like
Ajax+PHP 边学边练之四 表单
2009/11/27 PHP
phpmyadmin 常用选项设置详解版
2010/03/07 PHP
了解Joomla 这款来自国外的php网站管理系统
2010/03/11 PHP
深入解析PHP垃圾回收机制对内存泄露的处理
2013/06/14 PHP
PHP超全局数组(Superglobals)介绍
2015/07/01 PHP
关于PHP文件的自动运行方法分析
2016/05/13 PHP
微信封装的调用微信签名包的类库
2017/06/08 PHP
浅谈移动端之js touch事件 手势滑动事件
2016/11/07 Javascript
Node.js中多进程模块Cluster的介绍与使用
2017/05/27 Javascript
详解Angular 自定义结构指令
2017/06/21 Javascript
Vue.js实现价格计算器功能
2020/03/30 Javascript
vue渲染时闪烁{{}}的问题及解决方法
2018/03/28 Javascript
浅谈Angularjs中不同类型的双向数据绑定
2018/07/16 Javascript
JQuery复选框全选效果如何实现
2020/05/08 jQuery
JS访问对象两种方式区别解析
2020/08/29 Javascript
[01:25]2014DOTA2国际邀请赛 zhou分析LGD比赛情况
2014/07/14 DOTA
PHP网页抓取之抓取百度贴吧邮箱数据代码分享
2016/04/13 Python
tensorflow学习笔记之简单的神经网络训练和测试
2018/04/15 Python
Python Json模块中dumps、loads、dump、load函数介绍
2018/05/15 Python
Python3单行定义多个变量或赋值方法
2018/07/12 Python
python利用插值法对折线进行平滑曲线处理
2018/12/25 Python
python添加菜单图文讲解
2019/06/04 Python
Ubuntu20.04环境安装tensorflow2的方法步骤
2021/01/29 Python
Bench加拿大官方网站:英国城市服装品牌
2017/11/03 全球购物
Sandro Paris美国官网:典雅别致的法国时尚服饰品牌
2017/12/26 全球购物
哈萨克斯坦移动和数字技术在线商店:SatelOnline.kz
2020/09/04 全球购物
旅游管理专业个人求职信范文
2013/12/24 职场文书
周年庆典邀请函范文
2014/01/23 职场文书
中学劳技课教师的自我评价
2014/02/05 职场文书
致长跑运动员加油稿
2014/02/20 职场文书
家长通知书教师评语
2014/04/17 职场文书
学校先进集体事迹材料
2014/05/31 职场文书
尊师重教演讲稿
2014/09/04 职场文书
2019职场实习报告该怎么写?
2019/07/01 职场文书
一篇合格的广告文案,其主要目的是什么?
2019/07/12 职场文书
高中议论文(范文2篇)
2019/08/19 职场文书