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);
?>