Закрыть соединение с базой данных в классе php - PullRequest
0 голосов
/ 09 апреля 2020

У меня есть следующий класс:

class DB {
    private $connection;
    private $username;
    private $password;
    private $db_name;
    private $server;
    private $table;
    function __construct($server,$username,$password,$db_name,$table) {
        $this->server = $server;
        $this->db_name = $db_name;
        $this->username = $username;
        $this->password = $password;
        $this->table = $table;
        try {
            $this->connection = new mysqli($server,$username,$password,$db_name);
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
    private function delArray($mainArray,$delArray) {
        foreach ($mainArray as $mainIndex => $mainKey) {
            foreach ($delArray as $delIndex => $delKey) {
                if ($mainKey == $delKey) {
                    unset($mainArray[$mainIndex]);
                }
            }
        }
        return $mainArray;
    }
    public function separate($data,$type) {
        if ($type == 1) {
            $condition[0] = '';
            $condition[1] = '';
            foreach ($data as $index => $key) {
                if ($key == end($data)) {
                    $condition[0] .= $index;
                    $condition[1] .= "'".$key."'";
                } else {
                    $condition[0] .= $index.', ';
                    $condition[1] .= "'".$key."', ";
                }
            }
            return $condition;
        } else if ($type == 2) {
            $condition = '';
            foreach ($data as $index => $key) {
                if ($key == end($data)) {
                    $condition .= $index."='".$key."'";
                } else {
                    $condition .= $index."='".$key."', ";
                }
            }
            return $condition;
        }
    }
    private function tableColumn($nullValue=[]) {
        try {
            $result = [];
            $viewColumns = $this->connection->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".$this->db_name."' AND TABLE_NAME = '".$this->table."'");
            while($columnName=$viewColumns->fetch_assoc()){
                $result[] = $columnName['COLUMN_NAME'];
            }
            $result = $this->delArray($result,$nullValue);
            return $result;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
    public function selectData($condition=[],$receive=false) {
        try {
            $condition = ($condition == []) ? '' : " WHERE ".$this->separate($condition,2);
            $result = $this->connection->query("SELECT * FROM ".$this->table.$condition);
            if ($result->num_rows > 0) {
                if ($receive == true) {
                    $rowArray = [];
                    $i = -1;
                    while($row=$result->fetch_assoc()) {
                        $i += 1;
                        foreach ($this->tableColumn() as $index => $key) {
                            $rowArray[$i][$key] = $row[$key];
                        }
                    }
                    return $rowArray;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
    public function createData($data,$condition=[]) {
        try {
            $valueArray = $this->separate($data,1);
            if (empty($condition)) {
                return $this->connection->query("INSERT INTO ".$this->table." (".$valueArray[0].") VALUES (".$valueArray[1].")");
            } else {
                if ($this->selectData($condition) == false) {
                    return $this->connection->query("INSERT INTO ".$this->table." (".$valueArray[0].") VALUES (".$valueArray[1].")");
                } else {
                    return false;
                }
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
    public function updateData($data,$condition) {
        try {
            if ($this->selectData($condition) == true) {
                $condition = ($condition == []) ? '' : " WHERE ".$this->separate($condition,2);
                $data = $this->separate($data,2);
                $this->connection->query("UPDATE ".$this->table." SET ".$data.$condition);
            } else {
                return false;
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
    public function deleteData($condition) {
        try {
            if ($this->selectData($condition) == true) {
                $condition = ($condition == []) ? '' : $this->separate($condition,2);
                return $this->connection->query("DELETE FROM ".$this->table." WHERE ".$condition);
            } else {
                return 'does not exist';
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

Этот код работает отлично и проблем нет, но главная проблема в том, что Я не знаю куда поместить код закрытия базы данных !

Я пробовал много способов, например, я помещал его в __destruct function или в каждую функцию `` publi c, которую я поставил before return, но проблема не была решена и соединение закрывается дальше. помогите пожалуйста

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...