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);
?>
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.
Your misunderstanding is this:
return $this->sql;
You can't return
something of your choice in a constructor. The value returned by a constructor is always the object instance of that class.