Ok, This is sort of an involved problem, but any help or advice would be incredibly appreciated.
So I'm working with a site that (using .htaccess
) redirects all traffic to a load.php
. For any sql
functionality, I have an abstract class that has a lot of query statements as functions that pass parameters to define the specifics of each query.
e.g. $table->update("constraints")
I'm trying to figure out how to set the connection to the database on load.php
, and then set the connection as a variable ($mysqli
) that can then be referenced in my abstract query class without having to pass the parameter to every single query function call.
Again, any help or advice would be appreciated.
Here's an example of a function:
function clearTable (){
$mysqli = dbConnect::connect();
$sql = "TRUNCATE TABLE $this->tablename";
$mysqli->query($sql);
}
If I connect to the database in a construct function and set $this->mysqli
and replace $mysqli = dbConnect::connect();
with $mysqli = $this->mysqli
, none of the queries work. Though they work with a fresh reconnect on each call.
After looking through this a bit more, I can also create my
db::connect()
function to look like this:and pass that as
$this->mysqli
in the query functions fileYou should use Dependency Injection for this.
Basically it means that the class that needs the database connection doesn't create the connection, it just receives the already instasiated instance.
Example
In some init file:
Then in your class file:
A bonus for this is that you don't need to touch the QueryClass, if you ever want to start making some unit tests. You only need to pass a DB connection to a test database instead.