PHP - MySqli : A Multipurpose class for connecting to a MySql DataBase
You will see a PHP Class that can be tweaked as per requirements for connecting to MySql DataBase using PHPs MySqli extension .
Perks of DatabaseConnect class
- Can be used as a Standalone class
- Can be extended with your class
- Its Object can be passed as a parameter to your function etc
<?php
class DatabaseConnect
{
public $mysqli ;
public $connectionConfig ;
public function __construct($connectionConfig = null)
{
if ($connectionConfig == null)
{
// This is the default configuration for your class and you could pass custom configuration through the constructor
// For example default configuration will be
$this->connectionConfig = array(
'host' => 'YOUR_HOST', // Eg: localhost
'user' => 'USER_NAME', // Eg: root
'password' => '',
'database' => 'DATABASE',
'mysqlport' => 3306 // or any port
);
}
else
{
$this->connectionConfig = $connectionConfig;
}
}
// set custom configuration
public function setConfig($connectionConfig)
{
$this->connectionConfig = $connectionConfig;
}
// get configuration
public function getConfig()
{
return $this->connectionConfig;
}
// connects to database using $connectionConfig
public function connect()
{
$this->mysqli = new mysqli(
$this->connectionConfig['host'],
$this->connectionConfig['user'],
$this->connectionConfig['password'],
$this->connectionConfig['database'],
$this->connectionConfig['mysqlport']
);
if ($this->mysqli->connect_error) {
return [
'connected' => false,
'message' => $this->mysqli->connect_error,
];
} else {
return [
'connected' => true,
'message' => 'Connected to MySql server',
];
}
}
}
You could use it as a standalone script as shown below.If connect()["connected"] is true, then $mysqli will have connection to the database.
$db=new DatabaseConnect();
if($db->connect()["connected"]){
echo "CONNECTED TO DATABASE";
// connected, now $db->mysqli has connection to the database
// for example :
$qry="SELCT * From blah blah";
if($db->mysqli->query($qry)){
/// You could use it like this
}
}
else{
echo "FAILED TO CONNECT";
echo $db->connect()["message"];
}
You could extend it with your class as shown below.
class Accounts extends DatabaseConnect{
public function __construct(){
parent::__construct();
/*
if($this->connect()["connected"]){
// DO STUFF with $this->mysqli
}
*/
// passing custom config
$this->setConfig(
[
'host' => 'YOUR_HOST', // Eg: localhost
'user' => 'USER_NAME', // Eg: root
'password' => '',
'database' => 'DATABASE',
'mysqlport' => 3306 // or any port
]
);
if($this->connect()["connected"]){
// DO STUFF with $this->mysqli
}
}
}
You could pass it as a paramter to your function.
<?php
include('DatabaseConnect.php');
class DataHandler{
public function getData($mysqli){
$qry="SELECT * FROM BLAH";
if($mysqli->query($qry)){
// blah
}
}
}
$db=new DatabaseConnect();
$db->connect();
$dataHandler=new DataHandler();
$dataHandler->getData($db->mysqli);
So this is about our multi purpose class.