W
W
web5talker12017-09-24 00:37:44
PHP
web5talker1, 2017-09-24 00:37:44

How to close PDO mysql connection?

To close a connection in MySql PDO, do this:
$DBH = null;
But I'm using a wrapper:

Spoiler

<?php
class DB extends PDO
{
    public $error = false; // выводить сообщения об ошибках на экран? (true/false)
    
    public function __construct($dsn, $username='', $password='', $driver_options=array()) {
        try {
            parent::__construct($dsn, $username, $password, $driver_options);
                
            $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement', array($this)));
            
            $this->query("SET NAMES 'utf8'");                 
        } catch(PDOException $e) { 
            echo "Произошла ошибка в работе с базой данных...";
            exit();
        }
    }
    
    public function prepare($sql, $driver_options=array()) {
        try {
            return parent::prepare($sql, $driver_options);
        } catch(PDOException $e) { 
            $this->error($e->getMessage());
        }
    }
    
    public function query($sql) {
        try {
            return parent::query($sql);
        } catch(PDOException $e) { 
            $this->error($e->getMessage());
        }
    }
    
    public function exec($sql) {
        try {
            return parent::exec($sql);
        } catch(PDOException $e) { 
            $this->error($e->getMessage());
        }
    }
    
    public function error($msg) {
        if($this->error) {
            echo $msg;
        } else {
            echo "Произошла ошибка в работе с базой данных...";
        }
        exit();
    }
    
   
}

class DBStatement extends PDOStatement 
{
    protected $DBH;
    
    protected function __construct($DBH) {
        $this->DBH = $DBH;
    }
 
    public function execute($data=array())
{
    try {
        parent::execute($data);
        return $this; 
    } 
    catch(PDOException $e) {
        $this->DBH->error($e->getMessage());
    }
}
}
 
?>

And $DBH=null; does not work.
I can not understand in any way how it is necessary to close connection in this case.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FanatPHP, 2017-09-24
@web5talker1

Immediately throw in the trash this pitch hell, perverting all the principles of programming. Use the original PDO. Read Error reporting basics .
Make error handling common to all PHP.
At the same time, the problem with closing the connection will also disappear.

I
Ilya Gerasimov, 2017-09-24
@Omashu

type of

public function disconnect() {
  $this->DBH = null;
}

DB->disconnect();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question