I am making a Conexion.php class where I have the connection, and the UserHandler.php class where I am in charge of doing all the queries that I need related to the user.
connection.php
<?php
class Conexion {
private $hostname;
private $db;
private $user;
private $password ;
private $connection;
function __construct(){
$this->hostname = "localhost";
$this->db = "tb_crud";
$this->user = "root";
$this->password= "";
$this->connection = null;
}
public function conectar(){
if ($this->connection == null) {
$this->connection = mysqli_connect($this->hostname, $this->user, $this->password);
mysqli_select_db($this->connection,$this->db);
return $this->connection;
}
else{
return null;
}
}
public function desconectar(){
if ($connection != null) {
$connection = null;
}
}
public function getConnection(){
return $this->connection;
}
}
?>
UserHandler.php
<?php
include_once 'Conexion.php';
class UsuarioHandler{
private $conexion = null;
public function __construct(){
$this->conexion = new Conexion();
}
public function mostrarTodos(){
$this->conexion->conectar();
if ($this->conexion != null) {
$result = $this->conexion->prepare("SELECT * FROM usuarios");
$result->execute();
var_dump($result);
return $result;
}
else{
return null;
}
}
}
$qhu = new UsuarioHandler();
$qhu->mostrarTodos();
?>
If you look at the file UsuarioHandler.php I have this below the class:
$qhu = new UsuarioHandler();
$qhu->mostrarTodos();
I'm trying to make sure it works but it's throwing me some errors :
Fatal error: Uncaught Error: Call to undefined method Conexion::prepare() in...
Call to undefined method Conexion::prepare()
Your connection class does not contain the prepare method.
This method belongs to the database connection object, but not to your class.
You have a function that returns your connection object, the one that connects to the database and you are defined as
private $connection;
, that is on which you can do prepare...So your options are:
For example:
EITHER
For the latter, you could do: