-3

The Codes:

class mysql_db{
    private $conn;
    private function connect(){
        if(isset($this->$conn)){
            $this->$conn = new mysqli("localhost", "php_user", "php_pass", "db");
            if($this->$conn->connect_error)
                die("Connection failed: " . $this->$conn->connect_error);
        }
    }
    private function disconnect(){
        $this->$conn->close();
        unset($this->$conn);
    }

    public function getContent(){
        $this->connect();
        $stmt = $this->$conn->prepare("SELECT * FROM content");
        if($stmt->execute()){
            $stmt->bind_result($id, $type, $title, $text, $inserted);
            while($stmt->fetch()){
                printf("%s %s %s %s %s\n",$id, $type, $title, $text, $inserted);
            }
        }
        disconnect();
    }
}

$db = new mysql_db();
$db->getContent();

Result:

Notice: Undefined variable: conn in db.php on line 5
Notice: Undefined variable: conn in db.php on line 18
Fatal error: Cannot access empty property in db.php on line 18

The Question:

Why this happen, and how to fix it?

The Target:

Creating a connection class while limiting it user to use only PUBLIC function. Keeping all access to database inside it own class.

EDIT: Solution: It was only $ mistake.

1 Answers1

1

You should not use $ sign twice.

$this->$conn =

should be

$this->conn =

$ means referring a variable, if you are already referring , it , not need it twice , it gives errors.

Also use it in on line 18 as well . $this->conn->prepare("SELECT * FROM content");

Use $this->disconnect(); as it is not your custom function. You need to disconnect current object so use $this.

Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73