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

时间:2016-12-31 15:52:51

标签: php mysql database pdo

我目前正在尝试创建自己的自定义数据库类,这将允许我执行基本操作,例如插入,更新和从我的数据库中选择。我有我的插入功能的代码,但它插入两次,我不知道为什么。我已经有一段时间了,因为我已经搞乱了单身模式,今天我遇到了很多问题。任何帮助都会很棒。感谢

此处讨论的问题方法是insert()方法。它使用db()方法获取数据库连接的实例。

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)) {

        }
   }
}

致电Database::Insert

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

此代码确实有效,唯一的问题是它运行了两次。我认为这与类实例化两次有关但不确定。

1 个答案:

答案 0 :(得分:0)

我不得不重写该课程的大部分内容以使其正常工作。这是有效的代码:

// 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;
}