php 致命错误:未捕获的错误:在 null 上调用成员函数 select()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34810124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:14:18  来源:igfitidea点击:

Fatal error: Uncaught Error: Call to a member function select() on null

phpdatabaseoopmodel-view-controller

提问by Jamal Jubran

I am kinda new to OOP in php and I am facing this problem every time in the model but I can't find the error causing this.

我对 php 中的 OOP 有点陌生,每次在模型中我都面临这个问题,但我找不到导致这个的错误。

I get an error saying: Fatal error: Uncaught Error: Call to a member function select() on null in my modelin the getCategories function (See below code).

我收到一条错误消息:致命错误:未捕获的错误:在我的模型中的 getCategories 函数中调用成员函数 select() on null (见下面的代码)。

<?php

class model_additem extends model{
    public function __construct(){
        DB::setConnection(DB_ADMIN,DB_ADMIN_PASS);
    }

    public function insertItem($picName,$n,$d,$p,$ui,$ic,$pt,$pd="good"){
        $data = ["pic_name"=>$picName,"pic_desc"=>$pd,"pic_type"=>$pt];
        $img = parent::$db->saveTo("pictures")->setData($data)->execute();

        if($img){
            $imgId = parent::$db->lastInsertId();

            $data = ["name"=>$n,"description"=>$d,"price"=>$p,"image_id"=>$imgId,"owner_id"=>$ui,"category_id"=>$ic];
            $prod = parent::$db->saveTo("products")->setData($data)->execute();
            return $prod;
        }
        return false;
    }

    public function getCategories(){
        $data = parent::$db->select()->from('category')->fetch('all');
        if($data) return $data;
        return false;
    }


}

And here is my CONTROLLERfile:

这是我的控制器文件:

<?php

class controller_additem extends controller{
    public function __construct(){
        Load::view("admin".DS."header");
        Load::view('additem/additem');
        Load::view("admin".DS."footer");
        require_once 'CheckAdmin.php'; // Check if the user is admin to enter page + more.


    }

    public function index(){
        $item = $this->model("additem");
        if(isset($_POST["addItem"])){
            $iName = filter_input(INPUT_POST,"iName",FILTER_SANITIZE_MAGIC_QUOTES);
            $iDesc = filter_input(INPUT_POST,"iDesc",FILTER_SANITIZE_MAGIC_QUOTES);
            $iPrice = filter_input(INPUT_POST,"iPrice",FILTER_SANITIZE_NUMBER_FLOAT);
            $iCat = filter_input(INPUT_POST,"category",FILTER_SANITIZE_NUMBER_INT);
            $iPic = $_FILES["iPicture"];

            $extention = explode(".",$iPic["name"]);
            $ext = end($extention);
            //pre($iPic);
            //validation
            //if($iPic["size"]> 2000000){}
            $picName = $iName.time().'.'.$ext;
            if(move_uploaded_file($iPic["tmp_name"],ROOT . "public/images/" . $picName)){
                $userId = Session::get("userId");

                $result = $item->insertItem($picName,$iName,$iDesc,$iPrice,$userId,$iCat,$ext);
                if($result){
                    Session::set("result","Item has been inserted successfully");
                }else{
                    Session::set("result","Error occured");
                }

            }
        }
        $cats = $item->getCategories();
        $uName = Session::get("userData")["name"];
        Load::view("additem/additem",$cats);
    }
}

I also have a db class in my engine file that handles functions related to database and the select function is in there:

我的引擎文件中还有一个 db 类,用于处理与数据库相关的函数,并且 select 函数在其中:

class db{
    private static $db = null;
    private $sql = "";
    private $save_type;
    private $binded = array();
    private $query = '';
    private $last_insert_id;

    public function __construct(){
        if(self::$db == null){
            $user = DB_GUEST;
            $pass = DB_GUEST_PASS;
            if(Session::found("user_priv") == 'no'){
                $user = DB_USER;
                $pass = DB_USER_PASS;
            }
            if(Session::found("user_priv") == 'yes'){
                $user = DB_ADMIN;
                $pass = DB_ADMIN_PASS;
            }
            self::setConnection($user,$pass);
        }
    }

    public static function setConnection($user,$pass,$dbname=DB_NAME){
        try{
            self::$db = new PDO("mysql:host=localhost;dbname=$dbname",$user,$pass);
            self::$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
            self::$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
            self::$db->exec("SET NAMES utf8");
        }catch(PDOException $e){
            die($e->getMessage());
        }
    }

    public static function getDb(){
        if(self::$db == null){
            $user = DB_GUEST;
            $pass = DB_GUEST_PASS;
            if(Session::found("userId")){
                $user = DB_USER;
                $pass = DB_USER_PASS;
            }
            if(Session::found("admin")){
                $user = DB_ADMIN;
                $pass = DB_ADMIN_PASS;
            }
            self::setConnection($user,$pass);
        }
        return self::$db;
    }

    //SELECT [name,pass,email]
    public function select(array $select=[]){
        $sql = "SELECT ";
        if(empty($select)){
            $sql .= "*";
        }else{
            filter_array($select);
            $select = implode(",",$select);
            $sql .= string($select);
        }
        $this->sql = $sql;

        return $this;
    }

    //FROM
    public function from($tbl){
        $this->sql .= " FROM " . string($tbl);
        return $this;
    }

    //WHERE
    public function where(array $where){
        //filter_array($where);
        $sql = " WHERE ";
        foreach($where as $key => $val){
            $sql .= $key . " LIKE '".$val."' AND ";
        }

        $this->sql .= rtrim($sql," AND ");
        return $this;
    }

    //JOIN
    public function join(array $tbl,$type="LEFT JOIN"){
        $sql = " ".strtoupper($type)." ";
        $sql .= implode(",",$tbl);

        $this->sql .= $sql;
        return $this;
    }

    //ON
    public function on($cond1,$cond2){
        $sql = " ON ";
        $sql .= string($cond1) . " = " . string($cond2);

        $this->sql .= $sql;
        return $this;
    }

    //ORDER BY
    public function order_by($order_by, $order_type="ASC"){
        $sql = " ORDER BY ";
        $sql .= string($order_by)." ".strtoupper(string($order_type));

        $this->sql .= $sql;
        return $this;
    }

    //LIMIT
    public function limit($limit){
        $this->sql .= " LIMIT " . int($limit);
        return $this;
    }

    //FETCH
    public function fetch($fetch_type=""){
        $fetch = "fetch";
        if($fetch_type){
            $fetch = "fetchAll";
        }

        try{
            $query = self::$db->query($this->sql);
            $this->reset();
            return $query->$fetch();
        }catch(PDOException $e){
            die($e->getMessage());
        }
    }

    //saveTo
    public function saveTo($tbl,$type="insert"){
        $tbl = string($tbl);
        $this->save_type = strtolower(string($type));

        if($this->save_type == "update"){
            $sql = "UPDATE ";
        }elseif($this->save_type == "replace"){
            $sql = "REPLACE INTO ";
        }else{
            $sql = "INSERT INTO ";
        }

        $sql .= $tbl . " SET ";
        $this->sql = $sql;
        return $this;
    }

    //SET DATA
    public function setData(array $data,$filter="string"){
        $filter = string($filter);

        foreach($data as $colomn => $value){
            $colomn = string($colomn);
            $value = $filter($value);
            $this->binded[$colomn] = $value;
            $this->sql .= $colomn . "=:" . $colomn . ",";
        }
        //pre($this->binded);
        $this->sql = rtrim($this->sql,",");
        return $this;
    }

    //execute
    public function execute(){
        try{
            $this->query = self::$db->prepare($this->sql);
            if($this->binded){
                foreach($this->binded as $colomn => $value){
                    $this->bind($colomn,$value);
                }
            }
            $result = $this->query->execute();

            if($this->save_type == 'insert'){
                $this->last_insert_id = self::$db->lastInsertId();
            }
            $this->reset();
            return $result;

        }catch(PDOException $e){
            die($e->getMessage());
        }
    }

    //BIND
    private function bind($placeholder,$value,$filter="string",$bind_type="bindValue"){
        return $this->query->$bind_type(":".$placeholder,$filter($value),PDO::PARAM_STR);
    }

    public function lastInsertId(){
        return $this->last_insert_id;
    }

    //DELETE
    public function delete($tbl,$col=false){
        $this->sql = "DELETE ";
        if($col){
            $this->sql .= string($col)." ";
        }
        $this->sql .= "FROM " . string($tbl);
        return $this;
    }

    //TRUNCATE
    public function truncate($tbl){
        $this->sql = 'TRUNCATE ' . string($tbl);
        return $this;
    }

    //View Query
    public function viewQ(){
        echo $this->sql;
    }

    //RESET
    private function reset(){
        $this->sql = "";
        $this->save_type = "";
        $this->query = "";
        $this->binded = array();
    }
}

The thing is that if you look in the model at the saveTo function, it appears to work. However, select doesn't nor the functions that comes after it.

问题是,如果您在 saveTo 函数中查看模型,它似乎可以工作。但是, select 和它后面的函数都没有。

Please help me, I tried to search for this error but couldn't find the solution for my particular problem.

请帮助我,我试图搜索此错误,但找不到针对我的特定问题的解决方案。

Any help is highly appreciated! Thanks in advance.

任何帮助表示高度赞赏!提前致谢。

EDIT: Thanks everybody for your help! I figured it out. There was a mistake in the model class so the there wasn't connection with the db.

编辑:感谢大家的帮助!我想到了。模型类中存在错误,因此与数据库没有连接。

采纳答案by Erik Kalkoken

It appears that $db is not defined in the parent class. Which is model. Are you sure you initialized it?

似乎 $db 没有在父类中定义。哪个是模型。你确定你初始化了吗?

If you initialized it in the parent constructor (in the class model) you need to call it explicitly in your current constructor (in the class model_addItem). PHP will not do that automatically.

如果在父构造函数中(在类模型中)初始化它,则需要在当前构造函数中(在类 model_addItem 中)显式调用它。PHP 不会自动执行此操作。

回答by Last Templar

The error suggests that select()is called on a nullobject. Do a var_dump()on your parent::$dband make sure that the object is not actually empty.

该错误表明select()null对象上调用了它。做一个var_dump()对你parent::$db并确保该对象实际上没有空。

回答by Auris

Your problem is that parent::$dbis null. That means the database connection is not initialised. Start from figuring out why and work from there.

你的问题parent::$dbnull。这意味着数据库连接未初始化。从找出原因开始,然后从那里开始工作。