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.
This is the example for Object oriented style when extending mysqli class.
This file contains hidden or 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
<?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(); | |
} | |
} | |
?> |
This file contains hidden or 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
<?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); | |
?> |
Comments
Post a Comment