我在尝试将pdo数据库连接添加到我的MVC应用程序时遇到以下错误,我无法弄清楚我的代码有什么问题。如果我只是包含dbconnection.php并在需要时创建一个新实例,它就可以工作。但我真的想学习如何使用MVC。我是php的新手,我刚刚开始使用MVC。谁能弄清楚我做错了什么?而且我不想使用全局变量,所以我完全卡住了。 这是错误:
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
这是我的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;
}
}
这是我的基本模型代码:
class BaseModel {
protected $dbh;
public function __construct()
{
$database = new DbConnection();
$this->dbh = $database->dbcon('localhost', 'root', '6662257', 'mvc');
}
}
这是我的电影模特代码:
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();
}
}
答案 0 :(得分:2)
您需要在$this->dbh
中使用MovieModel
,而不是$dbh
。
我还应该提到您不需要SELECT查询的事务。从beginTransaction()
删除commit()
,rollback()
和getMovieList()
来电。
如果它只调用父的构造函数,那么你也不需要构造函数。默认情况下您具有此行为。从__construct()
MovieModel