我对pdo语句有一个可怕的问题.我的类基于Object生成SQL查询,然后将查询和参数转发到Bd类并执行,但数据被插入两次到数据库.
数据库中的表
CREATE TABLE IF NOT EXISTS `es_simple_object` (
`id_object` int(10) unsigned NOT NULL AUTO_INCREMENT,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`id_object`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Run Code Online (Sandbox Code Playgroud)
生成的查询
INSERT INTO es_simple_object (es_simple_object.id_object, es_simple_object.active) VALUES (NULL, ?)
Run Code Online (Sandbox Code Playgroud)
生成的params数组
Array
(
[0] => 1
)
Run Code Online (Sandbox Code Playgroud)
调用Db函数
static::$db = Db::getInstance();
static::$db->_execute($sql, $params);
Run Code Online (Sandbox Code Playgroud)
Bd Class(只是用于此工作的函数)
public static function getInstance()
{
if (!isset(self::$instance))
self::$instance = new Db();
return self::$instance;
}
private function __construct()
{
$connection = 'mysql:host='.$this->server.'; port='.$this->port.'; dbname='._DB_NAME_.'; charset='._DB_CHARSET_;
try
{
$this->link = new PDO($connection, _DB_USER_, _DB_PASSWD_);
$this->link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $ex)
{
Tools::_catchException($ex);
exit;
}
return $this->link;
}
public function _execute($sql, $params = array())
{
try
{
$pdoStatement = $this->link->prepare($sql);
$pdoStatement->execute($params == null ? array(null) : $params);
$this->rows_affected = $pdoStatement->rowCount();
$this->rows_returned = $pdoStatement->columnCount();
$this->last_id = $this->link->lastInsertId();
$this->result = $pdoStatement;
return $pdoStatement;
}
catch (PDOException $ex)
{
Tools::_catchException($ex, array($sql, $params));
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我没有更多的想法如何解决这个问题