diff --git a/_includes/Database.class.php b/_includes/Database.class.php new file mode 100644 index 0000000000000000000000000000000000000000..1f00096ddf817e968fce417f70d2d41cae00457f --- /dev/null +++ b/_includes/Database.class.php @@ -0,0 +1,32 @@ +<?php + +class Database +{ + public static $conn = null; + + public static function getConnection() + { + if (Database::$conn == null) { + $servername = "mysql.selfmade.ninja"; + $username = "raghav"; + $password = "R1a2g1h3av"; + $dbname = "raghav_photogram"; + + // Create connection in $conn variable + $conn = new mysqli($servername, $username, $password, $dbname); + // Check connection + if ($conn->connect_error) { + die("Connection failed: " . $conn->connect_error); //TODO: we can manage this error with exception handling in future classes... + } else { + // Returning the existing data of $conn + print("Connected newly"); + Database::$conn = $conn; + return Database::$conn; + } + } else { + // If database already connected it returns the existing value of $conn + print("Returned existed connection"); + return Database::$conn; + } + } +} diff --git a/libs/load.php b/libs/load.php index bd87be803e7fa3b6946aad59180061460302dcab..cf4827fa17c6e791c77661d0909c65b838c6dff0 100644 --- a/libs/load.php +++ b/libs/load.php @@ -2,6 +2,7 @@ // To include class files automatically include_once '_includes/Mic.class.php'; +include_once '_includes/Database.class.php'; function load_template($name) { @@ -22,17 +23,8 @@ function validate_credentials($username, $password) // Connecting to database function signup($user, $pass, $email, $phone) { - $servername = "mysql.selfmade.ninja"; - $username = "raghav"; - $password = "R1a2g1h3av"; - $dbname = "raghav_photogram"; - - // Create connection - $conn = new mysqli($servername, $username, $password, $dbname); - // Check connection - if ($conn->connect_error) { - die("Connection failed: " . $conn->connect_error); - } + // Store $conn values from class Database + $conn = Database::$conn; $sql = "INSERT INTO `auth` (`username`, `password`, `email`, `phone`, `block`, `active`) VALUES ('$user', '$pass', '$email', '$phone', '0', '1');"; diff --git a/test.php b/test.php index ab351713597a7a9f89167e824372a28d40c65134..e4a797ba157fba902715a75c1a72ebe4dc5f6db8 100644 --- a/test.php +++ b/test.php @@ -45,6 +45,10 @@ $mic1 -> setColorProxy("Red"); print("From private color: ". $mic1-> getColorProxy()); + // Check whether connection is established or returns existing connection + Database::getConnection(); + Database::getConnection(); + Database::getConnection(); ?>