我无法通过用户分类中的Admin类对象调用Admin类方法

时间:2019-10-01 17:08:49

标签: php oop error-handling

我无法检查数据库连接错误,也无法从数据库中获取数据。 即使输入了错误的数据库名称,也不会出现任何错误 我应该如何纠正我的代码?

数据库连接在该程序以外的其他程序中均能正常工作。我正在使用php7.0

config.php

    <?php
    if (!defined('DB_HOST')) define('DB_HOST','secret');
    if (!defined('DB_USER')) define('DB_USER','secret');
    if (!defined('DB_PASS')) define('DB_PASS','secret');
    if (!defined('DB_NAME')) define('DB_NAME','secret');
    ?>

Database.php

<?php
require_once "config.php";
class Database
{

    public $host = DB_HOST;
    public $user = DB_USER;
    public $pass = DB_PASS;
    public $dbname = DB_NAME;
    public $link;
    public $error;

    public function __construct()
   {
        $this->getConnect();
    }

    private function getConnect()
    {
        try {
                $this->link = new mysqli($this->host,$this->user,$this->pass,$this->dbname);
                if (mysqli_connect_errno()) {
                    $this->error = "Connection failed. ".$this->link->connect_error;
                throw new Exception("Error in database connection. ".$this->error, 1);

                }

        } catch (Exception $e) {
            echo $e->getMessage();
        }

    }

    //SELECT
    public function select($query)
    {
        try {
                if(!$result = $this->link->query($query)){
                    throw new Exception("Error Processing SELECT Request.".$this->link->error.__LINE__, 1);
                 }  

        } catch (Exception $e) {

            echo $e->getMessage();
        }   

        if ($result->num_rows > 0) {
            return $result;
        } else {
            return false;
        }

    }
}
?>

Admin.php

<?php
require_once "Database.php";
class Admin 
{
    private $db;
    public function __construct()
    {
        $this->$db = new Database();
    }

    public function getData()
    {

        $query = "select * from prog1";
        $result = $db->select($query);
        if($result != false){
            while ($row = $result->fetch_object()) {
                echo $row->name;
            }
        }
    }
}
?>

User.php

    <?php
    require_once 'Admin.php';
    class User
    {
        private $adminDo;
        public function __construct()
        {
            $this->adminDo = new Admin();
        }
        echo get_class($adminDo);
        $userDataPresentation = $this->adminDo->getData();
    }
    ?>

0 个答案:

没有答案