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

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择