0

I get this error: Call to a member function prepare() on a non-object in line 25. I have marked the line 25 that it's referring to; can someone please check and tell what's wrong? I tried all possible ways, but can't figure it out.

class db

class db {

public $connect;
private $username = "root";
private $password = "";
private $dns="mysql:host=localhost;dbname=etrharam_db";
private $method=array(PDO::MYSQL_ATTR_INIT_COMMAND=>"set name utf8");

public function connection(){
    $connect= new PDO($this->dns,$this->username,$this->password,$this->method);
    return $connect;
}/*connection*/

public function Idu($query,$data){
    $pre=$this->connect->prepare($query);
    foreach($data as $index=>$val){
        $pre->bindValue($index+1,$val);
    }
    $pre->execute();
}/*idu*/    

public function Select($query,$data){
    $pre=$this->connect->prepare($query);
    foreach($data as $index=>$val){
        $pre->bindValue($index+1,$val);
    }
    $pre->execute();
    $res=$pre->fetchAll(PDO::FETCH_ASSOC);
    return $res;
}/*select*/

}/*db*/

test.php

include ('oop.php');
$oop= new db;
$query="SELECT * FROM `newcoll_tbl` WHERE id=?";
$data=array('1');
$res=$oop->Select($query,$data);
print_r($res);

what is the problem? Thank you in advance.

  • dump $connect variable and see what in there – bxN5 Nov 06 '17 at 10:38
  • I think you forgot to call the function connection() to define your $connect variable. – Kozame Nov 06 '17 at 10:41
  • also, after you get your connection working, and other issues in this code, please take time to read about **[the usefulness of PDO wrappers](https://codereview.stackexchange.com/questions/29362/class-for-reducing-development-time/29394#29394)** – YvesLeBorg Nov 06 '17 at 11:25

1 Answers1

0

Your variable $connect is empty because it's never filled. Your function connection is never called, that's why your getting this error.

To fix this, you can do two things:

  • Call $oop->connection();
  • Change name of function connection to __construct so it runs automatically when calling $oop= new db();

I would recommend the second option

Huso
  • 1,501
  • 9
  • 14