-2

I am developing a eCommerce store for school project. i have several classes like this that uses same database connection. so i have to separate those.
1. how to use a single database connection file for all of my classes.I have sevaral classes same as this
2. I draw some use case and class diagram. if any one has experience in UML - (ecommerce ) can you verify those?

class abc {

 public $id;
 public $name;
 public $email;  
 public $db;   

 function __construct()
    {$this->db=new mysqli('localhost','root','','cart');}



public function newsletter_subcribe()
{$sql="insert into table (id,name,email) value('$this->id','$this->name','$this->email')";  
$this->db->query($sql);}
  • 1
    For the first question: Look into Dependency Injection. And take a look at prepared statements as well... – jeroen Dec 12 '16 at 08:04
  • The way you are using your database may be unsafe and vulnerable! Please read this: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php/60496#60496 – Hexaholic Dec 12 '16 at 08:07
  • Dependency injection is the way to go, that makes your code portable and flexible too. So you hand over the credentials to the constructor, typically in form of a static data object. – arkascha Dec 12 '16 at 08:07
  • This is for school project. i am asking how to use a single database connection file for all of my classes – CyberWarrior Dec 12 '16 at 08:08

1 Answers1

0

this class is do some query to your database for CRUD, the best thing you can do is make one more controller to access to this class, also make sure every function to do that is in private, not public.

so basicly the controller will post data to class to do CRUD. more like Model in CI.

CONTROLLER -->> YOUR CLASSS -->> DATABASE

CLASS A 
{
private function dbconnection()
{
}

private function a($param)
{
dbconnection();
//CRUD HERE
} 
}


CLASS B

main function()
{
//load class A here, and you can access all method
$result = a($param);
}
Evinn
  • 153
  • 1
  • 11
  • I did not get you. how to use a single database connection file for all of my classes.I have sevaral classes same as this. I don't want to type username and password db name and $db in every classes – CyberWarrior Dec 12 '16 at 08:16
  • you did not need to type username and password db name in every classes, Example : CLASS A, which contains db connection and all method to do CRUD (all method function is expect parameter to do CRUD), then in your controller or CLASS B, the thing you need to do is Load the Class A to access method function not the db connection, and passing parameter to CLASS A – Evinn Dec 12 '16 at 08:39