我正在尝试使用事务和mysql使用PDO来完成这项工作。我遇到的问题是,在我提交之前,事务就已经中断了。我知道这一点是因为我在连接上回显inTransaction()函数。
在我看来,这是因为我正在实例化一个PDODatabase类,然后在实际执行任何查询之前做一些其他编码工作,此时我会丢失事务。
实例化我的类
$pdo = new PdoDatabase;
$pdo->beginTransaction();
echo "first ".$pdo->transactionStarted()."<br />";
PdoDatabase类
public function __construct(){
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME;
$options = array(PDO::ATTR_PERSISTENT => TRUE, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try{
$this->_connection = new PDO($dsn, DB_USER, BD_PASS, $options);
} catch (PDOException $e){
$this->_error = $e->getMessage();
}
}
public function query($q){
if($this->_error != ''){
echo $this->_error;
} else {
$this->_stmt = $this->_connection->prepare($q);
}
}
public function bind($param, $value, $type = null){
//echo "<br>".$value."<br>";
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->_stmt->bindValue($param, $value, $type);
}
public function execute($class = null){
$object_array = array();
if($class !== null){
if($this->_stmt->execute()){
$this->_stmt->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, $class, null);
while($row = $this->returnRow()){
$object_array[] = $class::instantiate($row);
}
}
return $object_array;
} else {
return $this->_stmt->execute();
}
}
public function transactionStarted(){
return $this->_connection->inTransaction();
}
我是如何使用它(部分)
if(isset($_POST['id']) && $_POST['id'] != ''){
echo "id exists ".$pdo->transactionStarted()."<br />";
$bidder->getBidderById($_POST['id']);
echo "step 1 ".$pdo->transactionStarted()."<br />";
$bidder = $bidder->getList(0);
echo "step 2 ".$pdo->transactionStarted()."<br />";
$old_bidder = clone $bidder;
echo "step 3 ".$pdo->transactionStarted()."<br />";
$bidder_phones->getPhones($_POST['id']);
echo "step 4 ".$pdo->transactionStarted()."<br />";
$bidder_phones = $bidder_phones->getList();
echo "step 5 ".$pdo->transactionStarted()."<br />";
if($_POST['phone'] == ''){
// check to see if there are any phone numbers in the database already and delete if there is
foreach($bidder_phones as $bp){
$q = "delete from bidder_phones where id = :id";
$pdo->query($q);
$pdo->bind(":id", $bp->getId());
$pdo->execute();
//$bp->remove();
}
} else {
echo "phone to check ".$pdo->transactionStarted()."<br />";
$old_phone_numbers = array();
$new_phone_numbers = explode(',', $_POST['phone']);
foreach($bidder_phones as $bp){
// remove any unused phone numbers
if(!in_array($bp, $new_phone_numbers)){
$q = "delete from bidder_phones where id = :id";
$pdo->query($q);
$pdo->bind(":id", $bp->getId());
$pdo->execute();
//$bp->remove();
}
// push to an array to test the new numbers
array_push($old_phone_numbers, $bp->getPhone());
}
foreach($new_phone_numbers as $phone){
// adding new phone numbers
if(!in_array($phone, $old_phone_numbers)){
$new_phone = new BidderPhone;
$new_phone->setPhone($phone);
$new_phone->setBidderId($_POST['id']);
$pdo->save('BidderPhones', $new_phone);
//$new_phone->save();
}
}
}
正如您所看到的,我多次回显$pdo->transactionStarted()。这是一次尝试,看看我什么时候会输掉交易。我希望看到的是我的消息后面跟着一个1,以显示事务仍然处于活动状态。这就是我得到的:
first 1
id exists 1
step 1
step 2
step 3
step 4
step 5
phone to check
in save
before create
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'clickbid.bidder_phoneses' doesn't exist' in /var/www/classes/PdoDatabase.php:59 Stack trace: #0 /var/www/classes/PdoDatabase.php(59): PDOStatement->execute() #1 /var/www/classes/PdoDatabase.php(158): PdoDatabase->execute() #2 /var/www/classes/PdoDatabase.php(187): PdoDatabase->getFields('BidderPhones') #3 /var/www/classes/PdoDatabase.php(176): PdoDatabase->create('BidderPhones', Object(BidderPhone), false) #4 /var/www/admin/data/post_data.php(284): PdoDatabase->save('BidderPhones', Object(BidderPhone)) #5 {main} thrown in /var/www/classes/PdoDatabase.php on line 59
所以我在id存在之后就失去了事务,这是因为我在做其他编程,而不是准备查询和执行它们吗?我还有什么需要知道的吗?在过去的两天里,我一直在努力解决这个问题。问题是,在实际执行一些查询之前,我确实需要能够开始我的事务并做一些工作。有办法做到这一点吗?
提前感谢您的帮助。
编辑因此,我对代码进行了一些重大更改,并能够更准确地确定何时丢失活动事务。
我的保存方法看起来像这个
public function save($table, $object, $old_object = null){
echo "in save ".$this->transactionStarted()."<br />";
if($object->_id != ''){
echo "before update ".$this->transactionStarted()."<br />";
//return $this->update($table, $object, $old_object, $transaction);
if($this->update($table, $object, $old_object)){
echo "update true ".$this->transactionStarted()."<br />";
return true;
} else {
echo "update false ".$this->transactionStarted()."<br />";
return false;
}
} else {
echo "before create ".$this->transactionStarted()."<br />";
//return $this->create($table, $object, $transaction);
if($this->create($table, $object)){
echo "create true ".$this->transactionStarted()."<br />";
return true;
} else {
echo "create false ".$this->transactionStarted()."<br />";
return false;
}
}
}
在这种特殊的情况下,有一个来自对象的_id,所以$this->update是我们在这里调试的更新方法
private function update($table, $object, $old){
echo "in update ".$this->transactionStarted()."<br />";
$audit = new PdoDatabase;
echo "after new ".$this->transactionStarted()."<br />";
$aq = "insert into audit_trails
(table_name, table_id, user_id, field_name, original_value, new_value) values
(:table_name, :table_id, :user_id, :field_name, :original_value, :new_value)";
echo "before query ".$this->transactionStarted()."<br />";
$audit->query($aq);
echo "after query ".$this->transactionStarted()."<br />";
//$update = new PdoDatabase;
$binding = array();
echo "before field_names ".$this->transactionStarted()."<br />";
$field_names = self::getFields($table);
echo "after field_names ".$this->transactionStarted()."<br />";
$uc = new UserConfig;
$uc->getConfig();
$user = $uc->getList(0);
echo "before foreach ".$this->transactionStarted()."<br />";
foreach($field_names as $field){
$thisField = "_".$field['Field']."<br>";
$getField = 'get'.self::to_camel_case($field['Field']);
$method = $getField;
$class = self::to_camel_case($table);
$field_list = '';
if($field['Field'] == 'id'){
$where = 'where id = :id';
$binding[':id'] = ($object->$getField());
} else {
if(method_exists($class, $method)){
if($object->$getField() != $old->$getField()){
$field_list .= $field['Field']."= :".$field['Field'].", ";
$binding[':'.$field['Field']] = $object->$getField();
$audit->bind(':table_name', $table);
$audit->bind(':table_id', $object->getId());
$audit->bind(':user_id', $user->getUserId());
$audit->bind(':field_name', $thisField);
$audit->bind(':original_value', $object->$getField());
$audit->bind(':new_value', $old->$getField());
echo "before audit execute ".$this->transactionStarted()."<br />";
$audit->execute();
echo "after audit execute ".$this->transactionStarted()."<br />";
}
}
}
}
echo "before binding ".$this->transactionStarted()."<br />";
if(count($binding) > 1){
$q = "update ".self::singularToPlural($table)." set ";
foreach($binding as $key => $value){
if($key != ':id'){
$q .= str_replace(':', '', $key)." = ".$key.", ";
}
}
$q = rtrim($q, ", ");
$q .= ' '.$where;
//$update->query($q);
echo "before this query ".$this->transactionStarted()."<br />";
$this->query($q);
echo "after this query ".$this->transactionStarted()."<br />";
/*if($transaction && !$this->_stmt->inTransaction()){
$this->_stmt->beginTransaction();
}*/
foreach($binding as $key => $value){
//$update->bind($key, $value);
$this->bind($key, $value);
}
//$update->bind($id);
//return $update->execute();
echo "before this execute ".$this->transactionStarted()."<br />";
$stupid = $this->execute();
echo "after this execute ".$this->transactionStarted()."<br />";
return $stupid;
} else {
echo "before return true ".$this->transactionStarted()."<br />";
return true;
}
}
输出为
first 1
in save 1
before update 1
in update 1
after new 1
before query 1
after query 1
before field_names 1
before execute 1
after execute 1
after field_names 1
before foreach 1
before audit execute 1
before execute 1
after execute 1
after audit execute 1
before binding 1
before this query 1
after this query 1
before this execute 1
before execute 1
after execute 1
after this execute 1
update true
the save 1
second
after save
before commit
Fatal error: Uncaught exception 'PDOException' with message 'There is no active transaction' in /var/www/classes/PdoDatabase.php:86 Stack trace: #0 /var/www/classes/PdoDatabase.php(86): PDO->commit() #1 /var/www/admin/data/post_data.php(403): PdoDatabase->commit() #2 {main} thrown in /var/www/classes/PdoDatabase.php on line 86
从这一点我可以看到,当我们从更新返回到保存方法时,活动事务丢失了,我只是不确定为什么会这样。
再次感谢。
编辑添加getBidderById函数
public function getBidderById($bidder_id){
$pdo = new PdoDatabase;
$q = "select *
from bidders Bidder
where Bidder.id = :bidder_id
limit 1";
$pdo->query($q);
$pdo->bind(":bidder_id", $bidder_id);
$this->_bidders = $pdo->execute('Bidder');
if(!empty($this->_bidders)){
return true;
} else {
return false;
}
}
编辑添加创建方法
private function create($table, $object){
//$insert = new PdoDatabase;
$field_names = self::getFields($table);
foreach($field_names as $field){
$getField = 'get'.self::to_camel_case($field['Field']);
$method = $getField;
$class = self::to_camel_case($table);
if(method_exists($class, $method)){
if($field['Field'] != 'id'){
$fields = $field['Field'].", ";
$binding_fields = ":".$field['Field'].", ";
$binding[':'.$field['Field']] = $object->$getField();
}
}
}
$fields = rtrim($fields, ", ");
$binding_fields = rtrim($binding_fields, ", ");
$iq = "insert into ".self::singularToPlural($table)."
(".$fields.") values
(".$binding_fields.")";
$this->query($iq);
/*if($transaction && !$this->_stmt->inTransaction()){
$this->_stmt->beginTransaction();
}*/
foreach($binding as $key => $value){
$this->bind($key, $value);
}
if($this->execute()){
$object->setId($this->getConnection()->lastInsertId());
return true;
} else {
return false;
}
}
Hmz,我注意到您正在一个函数中实例化PdoDatabase,并使用$this->transactionStarted()。
这可能不是问题,但由于您使用的是持久连接,因此可能在其他类中启动一个新事务,从而导致对正在运行的事务的隐式提交。
if($this->create($table, $object)){
echo "create true ".$this->transactionStarted()."<br />";
return true;
}
如果在此函数中使用DDL语句(CREATE、ALTER、DROP、TRUNCATE等),则还将应用提交
MySQL中的某些语句会导致隐式提交。您可能正在进行的任何事务都已提交。例如,所有DDL语句都是这样做的。看见https://dev.mysql.com/doc/refman/5.6/en/implicit-commit.html了解更多信息。
令人惊讶的是,很难知道您的会话中是否有活动事务。在导致隐式提交的语句和查询可以是"commit"(不通过任何commit()函数,而是通过query()函数)的可能性之间,客户端无法确定是否仍有事务在进行。
这个问题对那些试图创建可重用DBAL的开发人员来说是一种祸害。
另请参阅我对"如何检测事务已启动?"的回答?
重新评论:
对于MySQL,PDO::inTransaction()
不可靠,因为PDO-MySQL驱动程序没有实现方法mysql_handle_in_transaction()
。MySQL C API不支持查询当前会话的事务状态。
因此,PDO类试图通过使用一个内部变量来进行最佳猜测,该变量在调用$dbh->beginTransaction()
时设置为1,在调用$dbh->commit()
或$dbh->rollback()
时设置为0。
但是,如果DDL语句导致隐式提交,则驱动程序不会收到任何事务结束的通知。因此,PDO中的内部变量可能与现实不同步。如果您调用$dbh->query('COMMIT')
,绕过PDO函数进行事务控制,也可能发生这种情况。
其他PDO驱动程序,例如PostgreSQL驱动程序,确实实现了获取当前事务状态的方法。
在这种情况下,我并不是说这就是你问题的原因。但是,尝试检测客户端中的事务状态并不总是有效的。
我不知道你的案子发生了什么。您仍然有几行调试输出没有共享代码。