I want to retrieve some Data from database using custom PHP MVC.
我想使用自定义PHP MVC从数据库中检索一些数据。
I created a Controller File
我创建了一个Controller文件
semestres.php
class Semestres extends Controller {
function __construct(){
parent::__construct();
}
public function index(){
$this->view->fetchSemestres = $this->model->fetchSemestres();
$this->view->render('semestres/index');
}
}
a Model
semestres_model.php
class Semestres_Model extends Model{
public function __construct(){
parent::__construct();
}
public function fetchSemestres(){
$stmt = $this->db->prepare("SELECT * FROM semestres");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
return $stmt->fetchAll();
}
}
and a View file index inside the folder semestre.
和文件夹semestre中的View文件索引。
foreach($this->fetchSemestres AS $key=>$value){
echo $value['intitule_semestre']."<br>";
}
But it gives me nothing !!!
但它没有给我什么!
The print_r($this->fetchSemestres) gives me an empty array
print_r($ this-> fetchSemestres)给了我一个空数组
Array ( )
数组()
// Update:
Database connection:
class Database extends PDO{
public function __construct(){
parent::__construct('mysql:host:localhost;dbname:planingexams', 'root', '');
}
}
Model.php
class Model{
function __construct(){
$this->db = new Database();
}
}
1 个解决方案
#1
Try this
class Database extends PDO{
public function __construct(){
parent::__construct('mysql:host=localhost;dbname=planingexams', 'root', '');
}
}
I tested your code locally and added
我在本地测试了你的代码并添加了
var_dump($stmt->errorInfo());
This gave me:
这给了我:
array(3) {
[0] =>
string(5) "00000"
[1] =>
int(1046)
[2] =>
string(20) "No database selected"
}
So after taking a good look at the database connection it seems you had to use = and not : to assign the values.
因此,在仔细查看数据库连接后,您似乎必须使用=而不是:分配值。
See:
$dbh = new PDO("pgsql:host=$host;port=5432;dbname=$db;user=$user;password=$pass");
From
#1
Try this
class Database extends PDO{
public function __construct(){
parent::__construct('mysql:host=localhost;dbname=planingexams', 'root', '');
}
}
I tested your code locally and added
我在本地测试了你的代码并添加了
var_dump($stmt->errorInfo());
This gave me:
这给了我:
array(3) {
[0] =>
string(5) "00000"
[1] =>
int(1046)
[2] =>
string(20) "No database selected"
}
So after taking a good look at the database connection it seems you had to use = and not : to assign the values.
因此,在仔细查看数据库连接后,您似乎必须使用=而不是:分配值。
See:
$dbh = new PDO("pgsql:host=$host;port=5432;dbname=$db;user=$user;password=$pass");
From