草庐IT

php - OOP 数据库连接/断开类

coder 2024-04-09 原文

我刚刚开始学习面向对象编程的概念,并编写了一个用于连接数据库、选择数据库和关闭数据库连接的类。到目前为止,除了关闭与数据库的连接外,一切似乎都没有问题。

    class Database {

    private $host, $username, $password;
    public function __construct($ihost, $iusername, $ipassword){
        $this->host = $ihost;
        $this->username = $iusername;
        $this->password = $ipassword;
    }
    public function connectdb(){
        mysql_connect($this->host, $this->username, $this->password)
            OR die("There was a problem connecting to the database.");
        echo 'successfully connected to database<br />';
    }
    public function select($database){
        mysql_select_db($database)
            OR die("There was a problem selecting the database.");
        echo 'successfully selected database<br />';
    }
    public function disconnectdb(){
        mysql_close($this->connectdb())
            OR die("There was a problem disconnecting from the database.");
    }
}

$database = new database('localhost', 'root', 'usbw');
$database->connectdb();
$database->select('msm');
$database->disconnectdb();

当我尝试断开与数据库的连接时,我收到以下错误消息:

Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in F:\Programs\webserver\root\oop\oop.php on line 53

我猜这不像将 connectdb 方法放在 mysql_close 函数的括号内那么简单,但找不到正确的方法。

谢谢

最佳答案

我会向您的类添加一个连接/链接变量,并使用析构函数。 这也将使您不必记住关闭连接,因为它是自动完成的。
这是您需要传递给 mysql_close() 的 $this->link。

class Database {

    private $link;
    private $host, $username, $password, $database;

    public function __construct($host, $username, $password, $database){
        $this->host        = $host;
        $this->username    = $username;
        $this->password    = $password;
        $this->database    = $database;

        $this->link = mysql_connect($this->host, $this->username, $this->password)
            OR die("There was a problem connecting to the database.");

        mysql_select_db($this->database, $this->link)
            OR die("There was a problem selecting the database.");

        return true;
    }

    public function query($query) {
        $result = mysql_query($query);
        if (!$result) die('Invalid query: ' . mysql_error());
        return $result;
    }

    public function __destruct() {
        mysql_close($this->link)
            OR die("There was a problem disconnecting from the database.");
    }

}

示例用法:

<?php
    $db = new Database("localhost", "username", "password", "testDatabase");

    $result = $db->query("SELECT * FROM students");

    while ($row = mysql_fetch_assoc($result)) {
        echo "First Name: " . $row['firstname'] ."<br />";
        echo "Last Name: "  . $row['lastname']  ."<br />";
        echo "Address: "    . $row['address']   ."<br />";
        echo "Age: "        . $row['age']       ."<br />";
        echo "<hr />";
    }
?>

编辑:
所以人们可以实际使用这个类,我添加了缺少的属性/方法。
下一步将是扩展查询方法,包括防止注入(inject)和任何其他辅助函数。
我做了以下更改:

  • 添加了缺失的私有(private)属性
  • 添加了__construct($host, $username, $password, $database)
  • connectdb()select() 合并到 __construct() 中,节省了额外的两行代码。
  • 添加了query($query)
  • 示例用法

如果我有错别字或错误,请留下建设性的评论,以便我可以为其他人修正。

编辑 23/06/2018

正如指出的那样,mysql 已经过时了,而且由于这个问题仍然经常受到访问,我想我应该发布一个更新的解决方案。

class Database {

    private $mysqli;
    private $host, $username, $password, $database;

    /**
     * Creates the mysql connection.
     * Kills the script on connection or database errors.
     * 
     * @param string $host
     * @param string $username
     * @param string $password
     * @param string $database
     * @return boolean
     */
    public function __construct($host, $username, $password, $database){
        $this->host        = $host;
        $this->username    = $username;
        $this->password    = $password;
        $this->database    = $database;

        $this->mysqli = new mysqli($this->host, $this->username, $this->password)
            OR die("There was a problem connecting to the database.");

        /* check connection */
        if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }

        $this->mysqli->select_db($this->database);

        if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }

        return true;
    }

    /**
     * Prints the currently selected database.
     */
    public function print_database_name()
    {
        /* return name of current default database */
        if ($result = $this->mysqli->query("SELECT DATABASE()")) {
            $row = $result->fetch_row();
            printf("Selected database is %s.\n", $row[0]);
            $result->close();
        }
    }

    /**
     * On error returns an array with the error code.
     * On success returns an array with multiple mysql data.
     * 
     * @param string $query
     * @return array
     */
    public function query($query) {
        /* array returned, includes a success boolean */
        $return = array();

        if(!$result = $this->mysqli->query($query))
        {
            $return['success'] = false;
            $return['error'] = $this->mysqli->error;

            return $return;
        }

        $return['success'] = true;
        $return['affected_rows'] = $this->mysqli->affected_rows;
        $return['insert_id'] = $this->mysqli->insert_id;

        if(0 == $this->mysqli->insert_id)
        {
            $return['count'] = $result->num_rows;
            $return['rows'] = array();
            /* fetch associative array */
            while ($row = $result->fetch_assoc()) {
                $return['rows'][] = $row;
            }

            /* free result set */
            $result->close();
        }

        return $return;
    }

    /**
     * Automatically closes the mysql connection
     * at the end of the program.
     */
    public function __destruct() {
        $this->mysqli->close()
            OR die("There was a problem disconnecting from the database.");
    }
}

示例用法:

<?php
    $db = new Database("localhost", "username", "password", "testDatabase");

    $result = $db->query("SELECT * FROM students");

    if(true == $result['success'])
    {
        echo "Number of rows: " . $result['count'] ."<br />";
        foreach($result['rows'] as $row)
        {
            echo "First Name: " . $row['firstname'] ."<br />";
            echo "Last Name: "  . $row['lastname']  ."<br />";
            echo "Address: "    . $row['address']   ."<br />";
            echo "Age: "        . $row['age']       ."<br />";
            echo "<hr />";
        }
    }

    if(false == $result['success'])
    {
        echo "An error has occurred: " . $result['error'] ."<br />";
    }
?>

关于php - OOP 数据库连接/断开类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9651038/

有关php - OOP 数据库连接/断开类的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  3. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  4. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  5. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  6. 世界前沿3D开发引擎HOOPS全面讲解——集3D数据读取、3D图形渲染、3D数据发布于一体的全新3D应用开发工具 - 2

    无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD

  7. FOHEART H1数据手套驱动Optitrack光学动捕双手运动(Unity3D) - 2

    本教程将在Unity3D中混合Optitrack与数据手套的数据流,在人体运动的基础上,添加双手手指部分的运动。双手手背的角度仍由Optitrack提供,数据手套提供双手手指的角度。 01  客户端软件分别安装MotiveBody与MotionVenus并校准人体与数据手套。MotiveBodyMotionVenus数据手套使用、校准流程参照:https://gitee.com/foheart_1/foheart-h1-data-summary.git02  数据转发打开MotiveBody软件的Streaming,开始向Unity3D广播数据;MotionVenus中设置->选项选择Unit

  8. 使用canal同步MySQL数据到ES - 2

    文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co

  9. ruby-on-rails - 创建 ruby​​ 数据库时惰性符号绑定(bind)失败 - 2

    我正在尝试在Rails上安装ruby​​,到目前为止一切都已安装,但是当我尝试使用rakedb:create创建数据库时,我收到一个奇怪的错误:dyld:lazysymbolbindingfailed:Symbolnotfound:_mysql_get_client_infoReferencedfrom:/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundleExpectedin:flatnamespacedyld:Symbolnotfound:_mysql_get_client_infoReferencedf

  10. STM32读取串口传感器数据(颗粒物传感器,主动上传) - 2

    文章目录1.开发板选择*用到的资源2.串口通信(个人理解)3.代码分析(注释比较详细)1.主函数2.串口1配置3.串口2配置以及中断函数4.注意问题5.源码链接1.开发板选择我用的是STM32F103RCT6的板子,不过代码大概在F103系列的板子上都可以运行,我试过在野火103的霸道板上也可以,主要看一下串口对应的引脚一不一样就行了,不一样的就更改一下。*用到的资源keil5软件这里用到了两个串口资源,采集数据一个,串口通信一个,板子对应引脚如下:串口1,TX:PA9,RX:PA10串口2,TX:PA2,RX:PA32.串口通信(个人理解)我就从串口采集传感器数据这个过程说一下我自己的理解,

随机推荐