dongpan5289 2017-06-10 19:35
浏览 107
已采纳

致命错误:调用未定义的方法connectDB :: prepare()

I tried to do a simple CRUD using a class connectDB to connect to a MySQL database. Then when I try to execute the method delRecipe of the class RecipesModel the system show me an error.

Fatal error: Call to undefined method connectDB::prepare()

Is the right way to call the method prepare()? Why is not recognized?

Here is the code of connectDB (file connectDB.php)

class connectDB {

    private $address='localhost';
    private $db_name='db-name';
    private $user='root';
    private $pswd='psswd';

    private $sql;

    public function __construct() {
        $this->sql = new mysqli($this->address,$this->user,$this->pswd,$this->db_name);
        if (mysqli_connect_error()) {
            die('Error de Conexion: '. mysqli_connect_errno().' - '.mysqli_connect_error());
        }
        return $this->sql;
    }

    public function __destruct() {
        if(!mysqli_close($this->sql)) {
            die('ERROR!:'.$this->sql->error);
        }
    }

    public function execute($query) {
        $res = $this->sql->query($query);
        if ($res) {
            return $res;    
        }
        else {
            die('ERROR!:'.$this->sql->error);
        }
    }
}

And the class that delete the row.

<?php
require_once('connectDB.php');

class RecipesModel {

    private $db;

    public function __construct() {
        $this->db = new connectDB();
    }

    public function delRecipe($id) {
        if (is_numeric($id)) {
            $sql = 'DELETE FROM t_platos WHERE ID_pl= ?';
            $this->db->prepare($sql);
            return $this->db->execute(array($id));
        }
    }
}

$recipe = new RecipesModel();
$res = $recipe->delRecipe(1);

?>
  • 写回答

2条回答 默认 最新

  • doutian4046 2017-06-10 19:42
    关注

    Your connectDB class does not have a method called prepare().

    You're probably trying to call $this->db->sql->prepare(), since in connectDB you store the actual database connection into $this->sql. However, since the $sql property is private, you can't do that.

    You'll either need to make $sql a public property, or create a method in your connectDB class to act as a proxy.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?