1

I'm trying to learn OOP along with PDO and prepared statements. I've made a database class which I believe is very simple.

I have a posts class and I want to echo all the data in this database, I have a constructor method which I want to call the database connection on however I believe I am doing this wrong and probably going about it the wrong way as I am getting the following error message:

Notice: Undefined variable: pdo in E:\xampp\htdocs\attendance\class.Register.php on line 18

Fatal error: Call to a member function prepare() on a non-object in E:\xampp\htdocs\attendance\class.Register.php on line 18

Any ideas on how I should go about calling my database correctly

posts.php

<?php
require 'database.php';

class Posts {

protected $Database;

     public function __construct() {
 $pdo = new Database();
     $this->pdo = $pdo;
        }

public function viewall() {

    $stmt = $pdo->prepare('SELECT * FROM posts');
    $stmt->execute();
    $stmt->fetch(); 
    }
}
$run = new Users();
$run->viewall();
?>

database.php

<?php

class Database {
    public $dbo;

    public function __construct() {
        // Connection information
        $host   = 'localhost';
        $dbname = 'testdb';
        $user   = 'root';
        $pass   = '';

        // Attempt DB connection
        try
        {
            $this->pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            //echo 'Successfully connected to the database!';
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
        
    }
    
     public function __destruct()
    {
        // Disconnect from DB
        $this->pdo = null;
        //echo 'Successfully disconnected from the database!';
    }
}
?>
Community
  • 1
  • 1

1 Answers1

1

You seem to be calling the method 'viewall' within the 'Users' class. However in the code you've shown the method 'viewall' is a member of the 'Posts' class.

$run = new Users();
$run->viewall();

Also you're setting the 'pdo' property, even though it doesn't exist within the class.

$pdo = new Database();
$this->pdo = $pdo;

Try changing

class Posts {

to

class Users {

and

protected $Database;

to

protected $pdo;
Buchow_PHP
  • 420
  • 2
  • 10