[MySQLi] Database Class
class database
{
// Declare database values
private $host = localhost;
private $username = username;
private $password = password;
private $database = database;
private $connection;
public function __construct()
{
$this->connect();
}
public function __deconstruct()
{
$this->close();
}
/*
Connect
Connect to the database
- Automatically called on load
*/
public function connect()
{
// Make connection
$this->connection = mysql_connect(
$this->host,
$this->username,
$this->password
);
// If unable to connect throw an error
if (!$this->connection) {
die("Could not connect: " . mysql_error());
}
// If unable to connect to database throw an error
if (!mysql_select_db($this->database)) {
die("Could not connect to database: " . mysql_error());
}
// Return true on successful connection
return true;
}
/*
Close
Close connection to the database
- Automatically called by __deconstruct
*/
public function close()
{
// Close the connection
$close = mysql_close($this->connection);
// If unable to close, terminate and throw error
if (!$close) {
die("Unable to close connection to the database");
}
// Return true if successful
return true;
}
}
$db = new database();
class form extends database
{
/*
Form functions
*/
}
$db->insert();
Source:
https://culttt.com/2012/05/23/how-to-connect-to-mysql-through-php