From b9cb7e7f831d5ec1d0523f3bbc2a467c849819c8 Mon Sep 17 00:00:00 2001 From: Raghav <raghavsmart1213@gmail.com> Date: Wed, 5 Mar 2025 07:58:17 +0000 Subject: [PATCH] Connect DB with class and Tested if conn exist return exist or create conn --- _includes/Database.class.php | 32 ++++++++++++++++++++++++++++++++ libs/load.php | 14 +++----------- test.php | 4 ++++ 3 files changed, 39 insertions(+), 11 deletions(-) create mode 100644 _includes/Database.class.php diff --git a/_includes/Database.class.php b/_includes/Database.class.php new file mode 100644 index 0000000..1f00096 --- /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 bd87be8..cf4827f 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 ab35171..e4a797b 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(); ?> -- GitLab