PDOException:第35行

时间:2015-04-23 13:35:48

标签: php pdo

以下是我在PDO中使用事务的示例:

我在浏览器中收到以下两个错误。

  • PDOException:......中没有活动的交易

  • 致命错误:未捕获的异常“PDOException”,消息“没有活动的交易”......

通过此链接提供的答案无法解决此问题(Uncaught exception 'PDOException' with message 'There is no active transaction'?

    <?php
    class conn
    {
      public $host = '';
      public $dbname = '';
      public $username = '';
      public $password = '';
      /**
      * @var object $db_connection The database connection
      */
      private $db_connection = null;

      public function __construct($host, $dbname, $username, $password)
      {
         $this->host = $host;
         $this->dbname = $dbname;
         $this->username = $username;
         $this->password = $password;
      }
      public function connected()
      {
        try 
        {
            $this->db_connection = new PDO('mysql:host='.$this->host.';     dbname='.$this->dbname.';charset=utf8mb4', $this->username, $this->password);
         return $this->db_connection;
    } 
    catch (PDOException $e) 
    {
    echo "Unable to connect to the PDO database: ". $e->getMessage(); 
    }
    }
    }

这些是我的数据库查询:

    <?php

    require('config/conn.php');
    $host = 'localhost';
    $dbname = 'dbname';
    $username = 'user';
    $password = 'pass';

   $db = new conn($host, $dbname, $username, $password);

   try 
   {
      $db->connected()->beginTransaction();
      $stmt = $db->connected()->prepare("INSERT INTO category_types        (name, cat_id) VALUES (:name, :value)");
      $stmt->bindParam(':name', $name);
      $stmt->bindParam(':value', $value);

     // insert one row
     $name = 'one';
     $value = 1;
     $stmt->execute();

     // insert another row with different values
     $name = 'two';
     $value = 2;
     $stmt->execute();


     $stmt = $db->connected()->prepare("INSERT INTO category_types2  (name, cat_id) VALUES (:name, :value)");
     $stmt->bindParam(':name', $name);
     $stmt->bindParam(':value', $value);

     // insert one row
     $name = 'one';
     $value = 1;
     if($stmt->execute())   

     $db->connected()->commit();


     } catch (Exception $e) {
      $db->connected()->rollBack();
      echo "Failed: " . $e->getMessage();
   }

我会很感激解决这个问题的线索。

1 个答案:

答案 0 :(得分:2)

这是因为您每次构建新连接时都会conn::connected()。将其更改为:

public function connected()
{
    if ($this->db_connection) return $this->db_connection;

    try {
        return $this->db_connection = new PDO('mysql:host='.$this->host.';dbname='.$this->dbname.';charset=utf8mb4',
                       $this->username, $this->password);
    } catch (PDOException $e) {
        echo "Unable to connect to the PDO database: " . e->getMessage(); 
    }
}