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条)

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端