Search code examples
phpoopmagic-methods

__set magic method for sql select statements


In here I'm going to create a class to work with SQL select using PHP __set magic method.My var_dump array return array(0) { } In the browser.What is the error i have did ?

class helper{

public function __set($table,$id){

    $dbConfig=array("localhost","itXXXXX","itXXXXX","u?XXXXXXX");
               $pardConfig=new PDO('mysql:host='.$dbConfig[0].';'.'dbname='.$dbConfig[1],$dbConfig[2],$dbConfig[3]);

               $sql=$pardConfig->prepare("SELECT * FROM ".$table."WHERE id=".$id);
               $sql->execute();
               $result=$sql->fetchALL(PDO::FETCH_ASSOC); 
               var_dump($result);
  }
        }

$helper = new helper();
$helper->pard_menu = 99;

Solution

  • Look at the error your query must have produced.

    You are missing a whitespace between the table name and the WHERE keyword:

    $sql=$pardConfig->prepare("SELECT * FROM ".$table."WHERE id=".$id);
    // HERE ------------------------------------------^
    

    change it to:

    $sql=$pardConfig->prepare("SELECT * FROM ".$table." WHERE id=".$id);