So I am basically re-doing some code on an existing system, mainly the database functions and I am putting them in a class rather than a function (currently the mysqli_connect DSN information is set in global variables and is being used every single time a query is being done which is why I am trying to clean this up but I am not trying to re-do this entire system all right now).
Current system has many PHP files that will include the main dbconnect.php file with a function of something like function db_query($query,$DSN){}
and we have in almost every single other file the actual SQL query being written out and then passed off as db_query($query);
and that is it.
I have moved over to something along the lines of the below code:
dbconnect.php
class Db {
protected static $connection;
function __construct() {
if (! isset($GLOBALS['DEBUG'])) { $GLOBALS['DEBUG'] = 0; }
}
public function connect() {
if(!isset(self::$connection)) {
self::$connection = new mysqli($GLOBALS['DSN']);
}
if(self::$connection === false) {
return false;
}
unset($GLOBALS['DSN']); //unset so that login info is not roaming around anymore now that the connection has been established
return self::$connection;
}
public function db_query($query) {
$connection = $this->connect();
$result = $connection->query($query);
return $result;
}
}
otherphpfile.php
include_once 'dbconnect.php';
(new Db()); //I have also tried new Db();
$query = "SELECT * FROM table;";
db_query($query); //I have to try to do it like this since 99.9% of the system is already using this method and I don't want to have to go through all the code and update it with something like:
$db = new Db();
$db->db_query($query);
I understand that $db = new Db(); $db->db_query($query);
is correct but I am trying to do it like this new Db();
without a variable assigned to it because all of the other functions for dbconnect.php
are written without a variable in front of the function call such as db_query($query);
like they are right now without me having to go and update all of them to $db->db_query($query);
.
I hope this makes sense and any suggestions would be great without compromising the benefit of using classes to begin with (AKA setting public static functions is just not worth it)
Thank you