I am working on a model of classes and views, not the MVC model. And I am having an error when I want to include the connection to the database.
class filehome.php
<?php
require_once 'db.php';
$conexion = new Dbh();
$conexion->connect();
class Home extends Theme{
public function __construct(){
$this->theme = new Theme();
}
public function home($tres){
$data['page_id'] = 1;
$data['page_title'] = 'Home';
$this->theme->getTheme($this, 'home', $data);
}
public function getlist(){
$sql = "SELECT * FROM lista";
$stmt = $conexion->connect()->prepare($sql); // linea 24
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
?>
class filedb.php
<?php
class Dbh{
private $host = 'localhost';
private $user = 'root';
private $pass = '';
private $dbName = '';
public function connect(){
$dsn = 'mysql:host='.$this->host.';dbname='.$this->dbName.';charset=utf8';
$pdo = new PDO($dsn, $this->user, $this->pass);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
}
}
?>
theme filehome.php
<?php headeradmin($data); ?>
<div class="container py-5">
<h1>Home</h1>
<?php
$lista = new Home();
$dato = $lista->getlist();
foreach($dato as $row){
echo $row['nombre'].'<br>';
}
?>
</div>
<?php footeradmin($data); ?>
The error I have is on line 24, it tells me that the variable is not defined $conexion
, but if it is and secondly it is a fatal error also on line 24
Warning: Undefined variable $connection in...
Fatal error: Uncaught Error: Call to a member function connect() on null in
I am not understanding what I am doing wrong. I appreciate the help in advance.
The first error is because your variable
$conexion
is not defined in your Home class , to fix it, you can instantiate it in the __constructor and then work with it using .$this->conexion
The second error, since the connection does not exist, your prepared statement fails.
Possible example: