PHP数据库处理封装类实例

本文实例讲述了PHP数据库处理封装类。分享给大家供大家参考,具体如下:

MySQL的操作相关类,检查并使用了mysqli

<?php
  //sample15_12.php
  class mydb {
    private $user;
    private $pass;
    private $host;
    private $db;
    //Constructor function.
    public function __construct (){
      $num_args = func_num_args();
      if($num_args > 0){
        $args = func_get_args();
        $this->host = $args[0];
        $this->user = $args[1];
        $this->pass = $args[2];
        $this->connect();
      }
    }
    //Function to tell us if mysqli is installed.
    private function mysqliinstalled (){
      if (function_exists ("mysqli_connect")){
        return true;
      } else {
        return false;
      }
    }
    //Function to connect to the database.
    private function connect (){
      try {
        //Mysqli functionality.
        if ($this->mysqliinstalled()){
          if (!$this->db = new mysqli ($this->host,$this->user,$this->pass)){
            $exceptionstring = "Error connection to database: <br />";
            $exceptionstring .= mysqli_connect_errno() . ": " . mysqli_connect_error();
            throw new exception ($exceptionstring);
          }
        //Mysql functionality.
        } else {
          if (!$this->db = mysql_connect ($this->host,$this->user,$this->pass)){
            $exceptionstring = "Error connection to database: <br />";
            $exceptionstring .= mysql_errno() . ": " . mysql_error();
            throw new exception ($exceptionstring);
          }
        }
      } catch (exception $e) {
        echo $e->getmessage();
      }
    }
    //Function to select a database.
    public function selectdb ($thedb){
      try {
        //Mysqli functionality.
        if ($this->mysqliinstalled()){
          if (!$this->db->select_db ($thedb)){
            $exceptionstring = "Error opening database: $thedb: <br />";
            $exceptionstring .= $this->db->errno . ": " . $this->db->error;
            throw new exception ($exceptionstring);
          }
        //Mysql functionality.
        } else {
          if (!mysql_select_db ($thedb, $this->db)){
            $exceptionstring = "Error opening database: $thedb: <br />";
            $exceptionstring .= mysql_errno() . ": " . mysql_error();
            throw new exception ($exceptionstring);
          }
        }
      } catch (exception $e) {
        echo $e->getmessage();
      }
    }
    //Function to perform a query.
    public function execute ($thequery){
      try {
        //Mysqli functionality.
        if ($this->mysqliinstalled()){
          if (!$this->db->query ($thequery)){
            $exceptionstring = "Error performing query: $thequery: <br />";
            $exceptionstring .= $this->db->errno . ": " . $this->db->error;
            throw new exception ($exceptionstring);
          } else {
            echo "Query performed correctly: " . $this->db->affected_rows . " row(s) affected.<br />";
          }
        //Mysql functionality.
        } else {
          if (!mysql_query ($thequery, $this->db)){
            $exceptionstring = "Error performing query: $thequery: <br />";
            $exceptionstring .= mysql_errno() . ": " . mysql_error();
            throw new exception ($exceptionstring);
          } else {
            echo "Query performed correctly: " . mysql_affected_rows () . " row(s) affected.<br />";
          }
        }
      } catch (exception $e) {
        echo $e->getmessage();
      }
    }
    //Function to return a row set.
    public function getrows ($thequery){
      try {
        //Mysqli functionality.
        if ($this->mysqliinstalled()){
          if ($result = $this->db->query ($thequery)){
            $returnarr = array ();
            while ($adata = $result->fetch_array ()){
              $returnarr = array_merge ($returnarr,$adata);
            }
            return $returnarr;
          } else {
            $exceptionstring = "Error performing query: $thequery: <br />";
            $exceptionstring .= $this->db->errno . ": " . $this->db->error;
            throw new exception ($exceptionstring);
          }
        //Mysql functionality.
        } else {
          if (!$aquery = mysql_query ($thequery)){
            $exceptionstring = "Error performing query: $thequery: <br />";
            $exceptionstring .= mysql_errno() . ": " . mysql_error();
            throw new exception ($exceptionstring);
          } else {
            $returnarr = array ();
            while ($adata = mysql_fetch_array ($aquery)){
              $returnarr = array_merge ($returnarr,$adata);
            }
            return $returnarr;
          }
        }
      } catch (exception $e) {
        echo $e->getmessage();
      }
    }
    //Function to close the database link.
    public function __destruct() {
      try {
        //Mysqli functionality.
        if ($this->mysqliinstalled()){
          if (!$this->db->close()){
            $exceptionstring = "Error closing connection: <br />";
            $exceptionstring .= $this->db->errno . ": " . $this->db->error;
            throw new exception ($exceptionstring);
          }
        //Mysql functionality.
        } else {
          if (!mysql_close ($this->db)){
            $exceptionstring = "Error closing connection: <br />";
            $exceptionstring .= mysql_errno() . ": " . mysql_error();
            throw new exception ($exceptionstring);
          }
        }
      } catch (exception $e) {
        echo $e->getmessage();
      }
    }
  }
  //Now, let us create an instance of mydb.
  $mydb = new mydb ("localhost","root","");
  //Select a database to use.
  $mydb->selectdb ("wps");
  //Now, let's perform an action.
  //$adata = $mydb->execute ("UPDATE cd SET title='Hybrid Theory' WHERE cdid='2'");
  //Then, let's try to return a row set.
  $adata = $mydb->getrows ("SELECT * FROM wp_terms");
  for ($i = 0; $i < count ($adata); $i++){
    echo $adata[$i] . "<br />";
  }
  $mydb->selectdb("test");
  $result = $mydb->execute("UPDATE user SET age = 23 WHERE id = 2");
  echo "<br />";
  echo $result;
?>

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php+mysql数据库操作入门教程》、《PHP基于pdo操作数据库技巧总结》、《PHP+MongoDB数据库操作技巧大全》、《php+Oracle数据库程序设计技巧总结》、《php+mssql数据库程序设计技巧总结》、《php+redis数据库程序设计技巧总结》、《php+mysqli数据库程序设计技巧总结》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

(0)

相关推荐

  • PHP文件与目录操作示例

    本文实例讲述了PHP文件与目录操作.分享给大家供大家参考,具体如下: 文件目录相关函数 <?php // 输出目录中的文件 function outputcurfiles ($allowedtypes, $thedir){ //首先,我们确保目录存在. if (is_dir ($thedir)){ //现在,我们使用scandir扫描目录中的文件. $scanarray = scandir ($thedir); //接着我们开始解析数组. //scandir()用"."和&quo

  • PHP面向对象程序设计方法实例详解

    本文实例分析了PHP面向对象程序设计方法.分享给大家供大家参考,具体如下: PHP5开始支持面向对象,示例如下: <?php class classname{ var $attr1; var $attr2; public $attribute; const PI = 3.14; // 构造函数 function __construct($param = 'default'){ echo "Constructor called with parameter $param<br /&g

  • PHP会话控制实例分析

    本文实例讲述了PHP会话控制.分享给大家供大家参考,具体如下: 关于cookie和session的测试代码: <?php session_start(); define('u','a'); define('p','1'); if (isset($_GET['r']) && $_GET['r']== 1) { unset($_COOKIE['username']); unset($_COOKIE['password']); unset($_SESSION['valid_login'])

  • Thinkphp框架中D方法与M方法的区别

    D()和M()方法的区别: D和M的区别主要在于 M方法不需要创建模型类文件,M方法不会读取模型类,所以默认情况下自动验证是无效的,但是可以通过动态赋值的方式实现 而D方法必须有创建模型类. 我们可以用下面两种方法去创建一个数据表的映射对象 第一种:$Test = D('Test') 第二种:$Test = new Model('Test') 虽然这两种都可以对数据进行select,insert,delete,udpate操作,在 数据验证上有很大的不同, 用第一种方式实例一个模型就会有数据检查

  • php的4种常用运行方式详解

    php的4种常用运行方式:CGI.FastCGI.APACHE2HANDLER.CLI. 1.CGI CGI即通用网关接口(common gatewag interface),它是一段程序,通俗的讲CGI就象是一座桥,把网页和WEB服务器中的执行程序连接起来,它把HTML接收的指令传递给服务器的执 行程序,再把服务器执行程序的结果返还给HTML页.CGI 的跨平台性能极佳,几乎可以在任何操作系统上实现. CGI方式在遇到连接请求(用户 请求)先要创建cgi的子进程,激活一个CGI进程,然后处理请

  • php 反斜杠处理函数addslashes()和stripslashes()实例详解

    php 反斜杠处理函数 addslashes():对输入字符串中的某些预定义字符前添加反斜杠,这样处理是为了数据库查询语句等的需要.这些预定义字符是:单引号 (') ,双引号 (") ,反斜杠 (\) ,NULL. stripslashes():删除由 addslashes() 函数添加的反斜杠.该函数用于清理从数据库或 HTML 表单中取回的数据.(若是连续二个反斜杠,则去掉一个,保留一个:若只有一个反斜杠,就直接去掉.) 默认情况下,PHP 指令 magic_quotes_gpc 为 on,

  • PHP常见字符串处理函数用法示例【转换,转义,截取,比较,查找,反转,切割】

    本文实例分析了PHP常见字符串处理函数用法.分享给大家供大家参考,具体如下: <?php $s = "hello world"; //整理 echo 'trim(); ltrim(); rtrim()'; echo '<br />'; echo '长度为: '.strlen($s); echo '<br />'; //大小写 echo '首字母大写: '.Ucfirst($s); echo '<br />'; echo '每个单词首字母大写:

  • 如何判断php mysqli扩展类是否开启

    如何判断php mysqli扩展类是否开启 php判断mysqli扩展类是否开启,源码如下: <?php /* by http://www.manongjc.com/article/1206.html */ function mysqlinstalled (){ if (function_exists ("mysql_connect")){ return true; } else { return false; } } function mysqliinstalled (){ i

  • PHP中addslashes()和stripslashes()实现字符串转义和还原用法实例

    本文实例讲述了PHP中addslashes()和stripslashes()实现字符串转义和还原用法.分享给大家供大家参考,具体如下: PHP中addslashes() 函数返回在预定义字符之前添加反斜杠的字符串. 预定义字符是: 单引号(') 双引号(") 反斜杠(\) NULL stripslashes() 函数删除由 addslashes() 函数添加的反斜杠. 用法示例如下: <?php $str="select * from `book` where bookname=

  • Bootstrap php制作动态分页标签

    学习了下bootstrap,刚好在用分页,就自己写了一个分页,然后结合bootstrap样式展现. bootstrap的分页格式: <ul class="pagination"> <li><a href="#">«</a></li> <li class="active"><a href="#">1</a></li> &l

  • PHP数组操作实例分析【添加,删除,计算,反转,排序,查找等】

    本文实例分析了PHP数组操作.分享给大家供大家参考,具体如下: PHP的数组是很重要的一部分.操作示例如下: <?php function br() { echo '<br />===============================================<br />'; } $arr1 = array(); $arr1[] = 'x'; $arr1[] = 'a'; $arr1[] = 'e'; $arr1[] = 'c'; $arr1[] = 'h'; /

  • PHP实现的文件操作类及文件下载功能示例

    本文实例讲述了PHP实现的文件操作类及文件下载功能.分享给大家供大家参考,具体如下: 文件操作类: <?php // Copyright 2005, Lee Babin (lee@thecodeshoppe.com) // This code may be used and redistributed without charge // under the terms of the GNU General Public // License version 2.0 or later -- www

随机推荐