试图构建一个静态数据库类,我可以从该类之外的任何函数访问它 [英] Trying to build a static database class that I can access from any function outside of the class

查看:28
本文介绍了试图构建一个静态数据库类,我可以从该类之外的任何函数访问它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:使用PDO而不是不推荐使用的方法将代码更改为现在可以工作的类代码

原始问题已得到回答,问题已解决.菲尔(Phil)使用 PDO 而不是传统的SQL来长大,所以看到该类还处于起步阶段,我决定开始迁移过程.

The original question was answered and the problem is solved. Phil brought up using PDO instead of traditional SQL so seeing as this class is in its infancy, I have decided to start the migration process.

class db
{
    private static $connection;
    const __DB__HOST__      = __DB__HOST__;
    const __DB_USERNAME__   = __DB_USERNAME__;
    const __DB_PASSWORD__   = __DB_PASSWORD__;
    const __DB_NAME__       = __DB_NAME__;


    private static function getConnection() {
        if (self::$connection === null) {

            $dsn = sprintf("mysql:dbname=".__DB_NAME__.";host=".__DB_HOST__, __DB_USERNAME__, __DB_PASSWORD__,"charset=utf8" );

            self::$connection = new PDO($dsn, self::__DB_USERNAME__, self::__DB_PASSWORD__, array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_EMULATE_PREPARES => false,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            ));
        }
        return self::$connection;
     }

    //Make the query
    private static function dbQuery($sql_string) {

        $conn = self::getConnection();

        $sth = $conn->prepare($sql_string);
        $sth->execute();

        return $sth;
    }

    //Return all results from sqlquery in array
    public static function dbDataArray($sql_string){

        $data = self::dbQuery($sql_string)->fetchAll();

        return $data;
    }

    public static function Value($sql_string){

        $data = self::dbQuery($sql_string)->fetchColumn();

        return $data;
    }
}

到目前为止,这是全班的学习进度,似乎效果很好.特别感谢Phil的所有支持.

This is the progress of the class so far and it seems to be working great. Special Thanks to Phil for all the support.

我们欢迎其他任何建议,将不胜感激.

Any other recommendations are welcome and will be greatly appreciated.

再次感谢.

基本上,我正在尝试构建可用于以下语法的数据库访问类

Basically I am trying to build a db access class that I can use with the following syntax

$test = db::dbDataArray("SELECT * FROM fw_settings");

如果不存在连接,该类将创建连接,因此我可以随时从该类中调用方法,而无需创建新实例.

The class will create the connection if one is not present so I can just call the methods from the class anytime without needing to create a new instance.

这是到目前为止我对具有单个功能的结构的了解.一旦使状态类可以用于单个查询项,我将添加所有其他功能.

Here is what I have so far for the structure with a single function. Once I can get the status class to work on a single query item I will add all the other functions.

class db
{
    public $connection;
    const __DB__HOST__      = __DB__HOST__;
    const __DB_USERNAME__   = __DB_USERNAME__;
    const __DB_PASSWORD__   = __DB_PASSWORD__;
    const __DB_NAME__       = __DB_NAME__;

    function __construct() {

        if (self::$connection == null){

             self::$connection = mysql_connect(__DB_HOST__,__DB_USERNAME__,__DB_PASSWORD__)
                or die('Unable to Connect to SQL Host'.__DB_HOST__);
             @mysql_select_db(__DB_NAME__)
                or die('Unable to Select DB: '.__DB_NAME__);
        }
    }

    //Regular SQL query such as delete, update, etc.
    public static function dbQuery($sql_string) {

        //Handle the rest of the SQL query here
        if (!$sqlResult = mysql_query($sql_string, self::$connection) ){
            //Let's output the MySQL error if we have one
            die('
                <div style="border:1px solid red;color:red;background:yellow;">
                    <p>'.$sql_string.'</p>
                    SQL Error:'. mysql_error(self::$connection).'
                </div>'
            );

        }
        else {
            //Return the sql result
            if (strpos($sql_string, "DELETE")){
                if (mysql_affected_rows($sqlResult) > 0){
                    return $sqlResult;
                }
                else{
                    return false;
                }
            }
            else{
                return $sqlResult;
            }
        }
    }

    //Return all results from sqlquery in array
    public static function dbDataArray($sql_string){

        $data = array();
        $dataQuery = self::dbQuery($sql_string);
        $i = 1;

        while(($row = mysql_fetch_assoc($dataQuery)) !== false){
            foreach($row AS $key=>$val){
                $data[$i][$key] = $val;
            }
            $i++;
        }
        return $data;
    }
}

这些常量是在该类之前加载的另一个文件中定义的,因此它们将存在.

The constants are defined in another file that is loaded before the class, so they will be present.

我现在遇到的错误如下.

The error that I am getting right now is as follows.

致命错误:访问未声明的静态属性:db :: $ connection

Fatal error: Access to undeclared static property: db::$connection

看起来连接很好.我只是无法使用dbQuery函数访问连接. dbQuery函数在所有其他函数中使用.

It looks like it is making the connection fine. I just can't access the connection using the dbQuery function. The dbQuery function is used in all the other functions.

这只是课程的开始,它基于我已经在使用的一组函数.

This is just the start of the class, and it is based on a group of functions I was already using.

一旦工作,最终的目标是能够将数据库名称传递给类并在该特定实例中访问该数据库,因此我可以在计划使用该数据库的项目中使用多个数据库.

The ultimate goal once it is working is to be able to pass a database name to the class and access that database in that specific instance, so I can use multiple databases in the projects I am planning to use this in.

推荐答案

为使您的类静态运行,您需要做一些事情.

In order for your class to operate statically, you need to do a few things.

首先,将连接设为静态,例如

First, make the connection static, eg

private static $connection;

第二,为什么所有下划线都是

Secondly, why all the underscores?

define('DB_HOST', 'localhost');
define('DB_NAME', 'your_db_name');
define('DB_USER', 'username');
define('DB_PASS', 'password');

为什么还要使用类常量呢?只需使用您已经定义的常量即可.

Also, why use class constants at all? Just use the constants you've already defined.

第三,丢失构造函数.您不能期望创建此类的实例 并静态使用它.我会采用延迟加载的方式进行连接

Third, lose the constructor. You cannot expect to create an instance of this class and use it statically. I would go for a lazy-load approach for the connection

private static function getConnection() {
    if (self::$connection === null) {
        $dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8',
            DB_HOST, DB_NAME);

        self::$connection = new PDO($dsn, DB_USER, DB_PASS, array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ));
    }
    return self::$connection;
}

然后,您的公共方法将在内部调用此方法.我还将充实您的dbDataArray方法,向您展示如何返回关联数组

Then, your public methods would call this method internally. I'll also flesh out your dbDataArray method to show you how to return an associative array

public static function dbDataArray($query, $params = array()) {
    $stmt = self::getConnection()->prepare($query);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

这篇关于试图构建一个静态数据库类,我可以从该类之外的任何函数访问它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆