Use of PDO in classes

后端 未结 4 988
面向向阳花
面向向阳花 2020-11-28 01:40

I have a few classes that perform some MySQL queries and prepared statements. However, I am lost in how to incorporate my PDO object within those classes. For example, I w

4条回答
  •  醉梦人生
    2020-11-28 02:35

    i found a better solution : when you have a PDO connection outside of your class and cant use that connection inside the class , send that PDO object to the constructor as a parameter

    ///thats my pdo connection

    $pdo_object = new PDO('mysql:host=localhost;dbname=blabla','user','pw');
    

    /// im creating the instance of that class as an obj

    $dataObj=new class_name($pdo_obj);
    

    ///// inside the class :::simplified

    class class_name{
    
    private $handler;//// this is what i use for PDO connection inside the class
    
    public function __construct($connection_name){
    
        if(!empty($connection_name)){
            $this->handler=$connection_name;
      ///its a great thing that holy php doesnt care much about variant types. any variant is able to carry any object (like PDO obj)
        }else{
            throw new Exception("cant connect bla bla...");
        }
    
    
    
    }/////contruct fx
    
    ////how i use that pdo connection which is implamented to a local var called handler  with any sql query is : 
    
    $dataSet= $this->handler->query("SELECT * FROM users WHERE ....");
    
    
    
    }////endof class
    

提交回复
热议问题