我怎样才能在不同的类中调用我的数据库类

时间:2013-09-17 15:22:52

标签: php oop pdo

我正在尝试学习OOP以及PDO和准备好的语句。我做了一个数据库类,我相信这很简单。

我有一个帖子类,我想要回显这个数据库中的所有数据,我有一个构造函数方法,我想调用数据库连接然而我相信我做错了,可能会以错误的方式进行因为我收到以下错误消息:

  

注意:未定义的变量:第18行的E:\ xampp \ htdocs \ attendance \ class.Register.php中的pdo

     

致命错误:在第18行的E:\ xampp \ htdocs \ attendance \ class.Register.php中的非对象上调用成员函数prepare()

关于如何正确调用数据库的任何想法

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!';
    }
}
?>

1 个答案:

答案 0 :(得分:1)

您似乎在“用户”类中调用方法“viewall”。但是在代码中你已经显示方法'viewall'是'Posts'类的成员。

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

此外,您正在设置'pdo'属性,即使它在类中不存在。

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

尝试更改

class Posts {

class Users {

protected $Database;

protected $pdo;
相关问题