没有错误:未调用PDO构造函数 [英] No error: PDO constructor was not called in

查看:118
本文介绍了没有错误:未调用PDO构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下午好.我昨天开始使用PDO,对此我有一些问题.我正在创建扩展类,该类无法正常工作,并且无法找到错误.

Good afternoon. I'm starting using the PDO yesterday, and I have some problem with this. I was creating extendet class, which doesn't work and I can't find the bug.

这是我的助手类的代码,用于工作女巫PDO:

This is code of my helper class, for work witch PDO:

    class EPDO extends PDO {
  /** Some identificator of connection*/
  public $db;

  /**
   * Creating new PDO connections
   */     
  public function __construct($dbhost, $dbname, $dbuser = 'root', $dbpass = '', $dbtype = 'mysql') {
    $db = new PDO($dbtype . ':host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
  } 

  /**
   * Insert into database with using transaction (if operation failed the changes go before)
   */     
  public function insert($statement) {
    $db->beginTransaction();

    $status = $db->exec($statement);
    if ($status) {
      $db->commit();  
    } else {
      $db->rollback();
    }
  } 
}

这是无效的代码:

$stm = $db->prepare('SELECT id FROM `startups` WHERE id = :id');
$params = array(':id' => $child->id);
$ok = $stm->execute($params);
$row = $stm->fetch(PDO::FETCH_ASSOC);

在此代码之前,我当然会通过以下方式调用连接:

Before this code I of course call the connections following way:

  require_once 'EPDO.php';

  try {
    $db = new EPDO('--server--', '--database--', '--user--', '--pass--');
  }
  catch (PDOException $err) {
    echo "Chyba spojeni: " . $err->getMessage();
  }

非常感谢,对不起我的英语.

Thank you very much, and sorry for my english.

推荐答案

问题是您正在扩展PDO类并覆盖构造函数,而没有调用构造函数.

The problem is that you're extending the PDO class and overriding the constructor, all without calling the constructor.

此外,每次创建新对象时,您实际上都在创建两个数据库连接.

Additionally, you're essentially creating two database connections every time you create a new object.

这应该有助于解决您的问题,并减少建立的连接:

This should help resolve your issue, and reduce the connections created:

class EPDO extends PDO {
    /** Some identificator of connection*/
    public $db;

    /**
     * Creating new PDO connections
     */     
    public function __construct($dbhost, $dbname, $dbuser = 'root', $dbpass = '', $dbtype = 'mysql') {
        parent::__construct($dbtype . ':host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
    } 

    /**
     * Insert into database with using transaction (if operation failed the changes go before)
     */     
    public function insert($statement) {
        $this->beginTransaction();
        $status = $this->exec($statement);
        if ($status) {
            $this->commit();  
        } else {
            $this->rollback();
        }
    }
}

这篇关于没有错误:未调用PDO构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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