Last active
February 24, 2016 20:19
-
-
Save HugoSilvaF/fd8bf82bd9f1f7ee8ceb to your computer and use it in GitHub Desktop.
PHP Database connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright © 2016 CrazyDev | |
This program is free software: you can redistribute it and/or modify | |
it under the terms of the GNU General Public License as published by | |
the Free Software Foundation, either version 3 of the License, or | |
(at your option) any later version. | |
This program is distributed in the hope that it will be useful, | |
but WITHOUT ANY WARRANTY; without even the implied warranty of | |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
GNU General Public License for more details. | |
You should have received a copy of the GNU General Public License | |
along with this program. If not, see <http://www.gnu.org/licenses/>. | |
*/ | |
<?php | |
class Database { | |
private $host = "localhost"; | |
private $username = "root"; | |
private $password = "root"; | |
private $database = "test"; | |
private $connection; | |
public function Database() { | |
if(func_num_args() > 0) { | |
call_user_func_array(array($this, "setFields"), func_get_args()); | |
} | |
$this->getMyConnection(); | |
if ($this->connection->connect_errno) { | |
echo 'Falied to connect mysqli, error: '.$this->connection->connect_error; | |
} | |
} | |
public function getMyConnection() { | |
if(!isset($this->connection)) { | |
$this->connection = $this->getNewConnection(); | |
} | |
return $this->connection; | |
} | |
public function getNewConnection() { | |
if(isset($this->host) || isset($this->username) || isset($this->password) || isset($this->database)) { | |
return new mysqli($this->host, $this->username, $this->password, $this->database) or die('Could not connect to server.' ); | |
} | |
} | |
public function cleanUpDB() { | |
if(!isset($this->connection)) { | |
$this->closeDatabase($this->connection); | |
} | |
} | |
public function closeDatabase($connection) { | |
if(isset($connection) && $connection instanceof mysqli) { | |
mysqli_close($connection) or die($connection->error); | |
} | |
} | |
public function setFields($host, $username, $password, $database) { | |
$this->host = $host; | |
$this->username = $username; | |
$this->password = $password; | |
$this->database = $database; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment