没有错误:没有调用PDO构造函数

 手机用户2502891267 发布于 2023-02-13 19:39

下午好.我昨天开始使用PDO,我有一些问题.我正在创建extendet类,它不起作用,我找不到bug.

这是我的助手类的代码,对于工作女巫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);

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

  require_once 'EPDO.php';

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

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

1 个回答
  • 问题是你正在扩展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') {
            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();
            }
        }
    }
    

    2023-02-13 19:41 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有