你如何在 Zend 2 的代码中处理数据库事务? [英] How do you make to work the database transaction in my code in Zend 2?

查看:30
本文介绍了你如何在 Zend 2 的代码中处理数据库事务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的模型中的代码:

This is my code from my model :

namespace Application\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;

class UsersTable extends AbstractTableGateway {

    public function __construct(Adapter $adapter) {
        $this->adapter = $adapter;
    }

    public function fetchAll() {

        $results = $this->adapter->query("SELECT * FROM users");
        $results = $results->execute();
        return $results->current();

    }
    public function insertNewUser($new_user_data){
        $ip = $_SERVER['REMOTE_ADDR'];
        try {
            $x = $this->adapter->getDriver()->getConnection()->beginTransaction();
            var_dump($x);

            $insert =   $this->adapter->query("INSERT INTO users (username,`name`,email,`password`, birthday,country,city,address,website,img_url,`date`,`update`,ip,email_confirm,`status`) values ('".$new_user_data['username']."','".$new_user_data['name']."','".$new_user_data['mail']."','".md5($new_user_data['password'])."','".$new_user_data['birthday']."','".$new_user_data['country']."','".$new_user_data['city']."','".$new_user_data['address']."','".$new_user_data['website']."','".$new_user_data['user_picture']."',NOW(),
                NOW(),'".$ip."','0','normal')");
            $insert->execute();

            $x = $this->adapter->getDriver()->getConnection()->commit();

        } catch (Exception $e) {
            $this->adapter->getDriver()->getConnection()->rollback();
            echo "Failed: " . $e->getMessage(); 
        }

    }

}

插入查询工作正常并被执行.但是 var_dump($x) 的结果是空的.为什么 ?我如何测试它以确保它有效?因为我没有收到错误或警告.

The insert query it works fine and it is executed. BUT the result of the var_dump($x) it is null. WHY ? and how do i test it to make sure that it works ? becuase i got no error or warnings.

推荐答案

如果 $x 为 null 没什么大不了的,因为方法 ConnectionInterface::beginTransaction() 应该返回 Connection 本身($this),它被称为流畅的界面.

It's not a big deal if $x is null because the method ConnectionInterface::beginTransaction() is supposed to return the Connection itself ($this), it's called fluent interface.

事实是并非所有驱动程序都正确实现了它.例如在 Mysqli 和 Pgsql 中,该方法没有返回.

The fact is that not all the drivers implements it correctly. For example in Mysqli and Pgsql the method has no return.

我不确定在此处使用事务是否相关...您只有一个插入,因此如果它失败,则无需回滚任何内容?

I'm not sure that it's relevant to use a transaction here ... You've got a single insert, so if it fails there's no need to rollback anything ?

当您希望多个数据库更改具有原子性时,事务非常有用(其中一个更改中的任何错误都将回滚整个更改).

A transaction is usefull when you want several database changes to be atomic (any error in one of theses changes will rollback the whole changes).

这篇关于你如何在 Zend 2 的代码中处理数据库事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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