1

I'm new to PHP and I'm trying to create a database class with inner join functionality but I'm getting this error:

Call to a member function InnerJoin() on a non-object in C:\xampp\htdocs\world\index.php on line 10

My code:

<?php 

class DB {
private static $_link = null,
               $_host = "127.0.0.1",
               $_pass = "",
               $_dbname = "mundo",
               $_user = "root",
               $_charset = "utf8";
private $_pdo,
        $_query,
        $_count = 0,
        $_error = false,
        $_results;

private function __construct() {
    $this->_pdo = new PDO("mysql:host=".self::$_host.";dbname=".self::$_dbname,self::$_user,self::$_pass);
}

public static function getLink() {
    if(!isset(self::$_link)) {
        self::$_link = new DB();
    }
    return self::$_link;
}

public function Get($table) {
    return $this->_query = "SELECT * FROM ".$table;
}

public function Go() {
    if($this->_query = $this->_pdo->prepare($sql)) {
        echo "prepared";
    }
}

public function InnerJoin($table1, $column1, $table2, $column2){
    return $this->_query = $this->_query." INNER JOIN ".$table2." ON ".$table1.".".$column1." = ".$table2.".".$column2;
}
}
?>

and in my index.php i have this:

<?php 
$DB = DB::getLink()->Get("paises")->InnerJoin("paises","Id_Continente","Continentes","Id_Continente")->Go();
?>

I hope you can help me, thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
DaveSanchez
  • 13
  • 1
  • 5

2 Answers2

2

Because you're returning $this->_query from Get function where as it requires to return a complete object to use it again,

public function Get($table) {
    $this->_query = "SELECT * FROM ".$table;
    return $this;
}

For more detail read Method Chaining.

Community
  • 1
  • 1
Rikesh
  • 26,156
  • 14
  • 79
  • 87
0
$DB = DB::getLink()->Get("paises")->InnerJoin("paises","Id_Continente","Continentes","Id_Continente")->Go()

you have here 3 method calls in one instruction... there is no problem with this when each function returns the object that has to call the next function.

But this is not happening here.

getLink() initialices the object DB and retunrns it, so next its ok:

DB->Get("paises")

this returns a boolean telling if the assignment $this->_query = "SELECT * FROM ".$table; succeeded... and here is when you fail:

1->InnerJoin

try not doing all at once, examining the return and constructing the next step accordingly.

javier_domenech
  • 5,995
  • 6
  • 37
  • 59