0

I'm working on a project where I have several different classes that need to connect to a MySQL database. My question is how do I accomplish this from inside the instantiated classes efficiently. I've read that opening and closing multiple connections is a bad idea and using globals also isn't a great option... So what other options are there? Is there a standard or best practive for accessing databases in this kind of situation? I'm still a beginning programmer.

1
  • 2
    please upload your code here. Commented Apr 2, 2014 at 2:10

1 Answer 1

2

Establish a connection then pass that connection object to each of the classes that require it as an argument to the constructor.

class myClass {

 function __construct($db) {
  $this->db = $db;
 }
 function doStuff($someQuery) {
  $result = $this->db->query($someQuery);
  // fetch data here...
  return $someData;
 }
}

Then

$db = new mysqli($host, $user, $password, $dbname);
$someObject = new myClass($db);
$data = $someObject->doStuff($myQuery);
Sign up to request clarification or add additional context in comments.

6 Comments

OK, so then when I pass off the connection as a parameter, it would just be getting passed off as a reference to the original connection, is that right?
That's precisely what happens
I take it this works just as well if I created a class for my database connection and passed off the object as a parameter?
That'll depend on the class you create, but in principle it should be fine.
Could you expand on that? If I create a class, should I create a static class just so I can ensure there's only one instance of that class? And would you say creating a class is a better option or just creating a normal connection like you specified in your answer? Is there any downsides, such as security concerns or anything?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.