Connect to database in php using class with constructor

PHP has different ways to connect to MySQL database.
This is the example for Object oriented style when extending mysqli class.

<?php
//Connect to database in php using class with constructor
class DBHandler
{
private $DB_HOST = "localhost"; //localhost
private $DB_USER = "root"; //root
private $DB_PASS = "pinturp1"; // ""
private $DB_NAME = "ShemaDB"; //test
public $mysqli;
public function __construct() {
// CONNECT TO THE DATABASE
$this->mysqli = new mysqli($this->DB_HOST, $this->DB_USER, $this->DB_PASS, $this->DB_NAME);
if (mysqli_connect_errno()) {
throw new Exception("Unable to connect to the database. Error number: " . $this->mysqli->connect_errno);
}
$this->mysqli->set_charset("uft8");
}
public function __destruct() {
//We are done with the database. Close the connection handle.
$this->mysqli->close();
}
}
?>
view raw dbconnect.php hosted with ❤ by GitHub
<?php
include('classes/dbconnect.php');
$obj = new DBHandler();
/*$sql="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";
// Execute query
if (mysqli_query($obj->mysqli,$sql))
{
echo "Table persons created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($obj->mysqli);
}*/
$GetPersion = mysqli_query($obj->mysqli,"SELECT * FROM Persons");
// Execute query
if (!$GetPersion)
{
echo "Error found: " . mysqli_error($obj->mysqli);
}
echo 'Person Count---'. mysqli_num_rows($GetPersion);
?>
view raw Results.php hosted with ❤ by GitHub

Comments

Popular posts from this blog

Login with facebook using coldfusion

Create CSV file in Coldfusion Using CFFile

Get Previous One Day Data in Sql Server