I'm getting the following error when trying to add a pdo database connection to my MVC application and I can't figure out what is wrong with my code. It works if I just include the dbconnection.php and create a new instance whenever I need to. But I really want to learn how to work with MVC. I'm quite new in php and I'm just started with MVC. Can anyone figure out what I'm doing wrong? And I don't wanna use globals so I'm completely stuck. Here is the error:
Notice: Undefined variable: dbh in C:\xampp\htdocs\me1520\php\uppgift-MVC\model\MovieModel.php on line 17
Fatal error: Call to a member function beginTransaction() on a non-object in C:\xampp\htdocs\me1520\php\uppgift-MVC\model\MovieModel.php on line 17
This is my dbconnection:
class DbConnection {
private $host = DB_HOST;
private $dbuser = DB_USER;
private $dbpass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
public function dbcon($host, $dbuser, $dbpw, $db) {
$pre = 'mysql:host='.$host.';dbname='.$db.;
$this->dbh = new PDO($pre, $dbuser, $dbpw, array(PDO::ATTR_PERSISTENT => true));
$this->dbh->exec('SET CHARACTER SET utf8',);
return $this->dbh;
}
}
And here is my basemodel code:
class BaseModel {
protected $dbh;
public function __construct()
{
$database = new DbConnection();
$this->dbh = $database->dbcon('localhost', 'root', '6662257', 'mvc');
}
}
And this is my moviemodel code:
include_once 'BaseModel.php';
include_once 'Movie.php';
class MovieModel extends BaseModel {
public function __construct()
{
parent::__construct();
}
public function getMovieList() {
try {
$dbh->beginTransaction();
$sql = $dbh->prepare("SELECT * FROM movies ORDER BY movie_id");
$sql->execute();
$movies = array();
while($row = $sql->fetch()){
$id = $row['movie_id'];
$title = $row['movie_title'];
$description = $row['movie_des'];
$link = $row['movie_link'];
$movies[$title] = new Movie($id, $title, $description, $link);
}
return $movies;
$dbh->commit();
}
catch (Execption $e) {
$dbh->rollback();
}
}