dqwolwst50489 2016-12-31 15:52
浏览 39
已采纳

查询在自定义PDO数据库类中运行两次

I'm currently attempting to create my own custom database class that will allow me to do basic things such as insert, update, and select from my database. I have the code working for my insert function but it's inserting twice and I'm not sure why. It's been a while since I've messed with the singleton pattern and am having quite a few issues today. Any help would be great. Thanks

The issue method in question here is the insert() method. It uses the db() method to get it's instance of the database connection.

Database.php

class Database {
    // Class Properties
    private static $_instance;
    public $pdo;

    /**
     * Returns a database connection
     * @return resource Database Connection
     */
    private static function db() {
        // Return Database Connection
        return Database::getInstance()->getConnection();
    }

    private function getConnectionProperties($property) {
        return $GLOBALS['config']['database'][$property];
    }

    /**
     * Singleton for database connection
     * @return class Returns one instance of the Database class
     */
    public static function getInstance() {
        if(!self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * Connects to database
     * @return mysql PDO connection to mysql databse
     */
    public function getConnection() {
        try {
            //Attempt to connect
            $this->pdo = new PDO('mysql:host=' . $this->getConnectionProperties('host') . ';dbname=' . $this->getConnectionProperties('database') , $this->getConnectionProperties('username'), $this->getConnectionProperties('password'));

            //Return connection
            return $this->pdo;
        } catch (PDOException $e) {
            throw new PDOException($e);
        }
    }

    public static function insert($table, $params) {
        // Define initial query
        $query = "INSERT INTO `{$table}` (";

        // Format rows to insert
        foreach(array_keys($params) as $field) {
            $fields .= $field . ",";
            $bindParams .= ":" . $field . ",";
        }

        // Add rows and bind params to query
        $query .= rtrim($fields, ',') . ") VALUES(" . rtrim($bindParams, ',') . ")";

        // Prepare Query
        $preparedQuery = self::db()->prepare($query);

        foreach($params as $key => $value) {
            $queryParams[':' . $key] = $value;
        }

        //Execute Query
        if($preparedQuery->execute($queryParams)) {

        }
   }
}

Calling Database::Insert

Database::insert("test_table", [
    'username' => "Joe_Scotto",
    'name' => "Joe"
]);

This code does work, the only issue is that it runs twice. I think this has something to do with the class getting instantiated twice but am not sure.

  • 写回答

1条回答 默认 最新

  • douzhang3898 2016-12-31 21:23
    关注

    I had to rewrite a large portion of the class to get it working. This is the code that worked:

    // Class Properties
    private static $_instance = null;
    private $_pdo;
    
    /**
     * Grabs connection variables
     * @param  string $property Variable to grab from the config file
     * @return string           Returns a config value
     */
    private function getConnectionProperties($property) {
        return $GLOBALS['config']['database'][$property];
    }
    
    /**
     * Returns pdo connection
     * @return resource PDO Object
     */
    public function getConnection() {
        return $this->_pdo;
    }
    
    /**
     * Connects to database
     * @return mysql PDO connection to mysql databse
     */
    public function __construct() {
        try {
            //Attempt to create connection
            $this->_pdo = new PDO('mysql:host=' . $this->getConnectionProperties('host') . ';dbname=' . $this->getConnectionProperties('database') , $this->getConnectionProperties('username'), $this->getConnectionProperties('password'));
        } catch (PDOException $e) {
            throw new PDOException($e);
        }
    }
    
    /**
     * Singleton for database connection
     * @return class Returns one instance of the Database class
     */
    public static function getInstance() {
        if(!self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    
    /**
     * Inserts into the database
     * @param  string $table  The table to insert into
     * @param  array  $params Key and value pairs for use within the query
     * @return bool           True on success, false on failure
     */
    public static function insert($table, $params) {
        // Define initial query
        $query = "INSERT INTO `{$table}` (";
    
        // Format rows to insert
        foreach($params as $key => $value) {
            $fields .= $key . ",";
            $bindParams .= ":" . $key . ",";
            $queryParams[':' . $key] = $value;
        }
    
        // Add rows and bind params to query
        $query .= rtrim($fields, ',') . ") VALUES(" . rtrim($bindParams, ',') . ")";
    
        // Prepare Query
        $preparedQuery = self::getInstance()->getConnection()->prepare($query);
    
        // Attempt to execute Query
        if(!$preparedQuery->execute($queryParams)) {
            return false;
        }
    
        // If everything passes, return true
        return true;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集