致命错误:调用未定义的方法connectDB :: prepare() [英] Fatal error: Call to undefined method connectDB::prepare()
问题描述
我试图使用类connectDB连接到MySQL数据库来做一个简单的CRUD.然后,当我尝试执行RecipesModel类的delRecipe方法时,系统向我显示错误.
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.
致命错误:调用未定义的方法connectDB :: prepare()
Fatal error: Call to undefined method connectDB::prepare()
调用方法prepare()的方法正确吗?为什么不被识别?
Is the right way to call the method prepare()? Why is not recognized?
这是connectDB的代码(文件connectDB.php)
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);
}
}
}
以及删除行的类.
<?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);
?>
推荐答案
您的connectDB
类没有拥有一种名为prepare()
的方法.
Your connectDB
class does not have a method called prepare()
.
您可能正在尝试调用$this->db->sql->prepare()
,因为在connectDB
中,您将实际的数据库连接存储在$this->sql
中.但是,由于$sql
属性是private
,所以您不能这样做.
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.
您需要将$sql
设置为public
属性,或者在connectDB
类中创建一个方法以充当代理.
You'll either need to make $sql
a public
property, or create a method in your connectDB
class to act as a proxy.
这篇关于致命错误:调用未定义的方法connectDB :: prepare()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!