检查以下几个方面:
以下是一个可能的代码示例:
模型代码:
class ProductsModel {
private $db;
public function __construct($database) {
$this->db = $database;
}
public function getAllProducts() {
$query = "SELECT * FROM products";
$result = $this->db->query($query);
return $result;
}
...
}
控制器代码:
class ProductsController {
private $model;
public function __construct($model) {
$this->model = $model;
}
public function getAllProducts() {
$result = $this->model->getAllProducts();
return $result;
}
...
}
视图代码:
class ProductsView {
public function render($data) {
echo "";
echo "Name Price ";
echo "";
foreach($data as $row) {
echo "{$row['name']} {$row['price']} ";
}
echo "
";
}
...
}
在 index.php 或其他主要入口文件中调用模型、控制器和视图:
require_once 'Models/ProductsModel.php';
require_once 'Controllers/ProductsController.php';
require_once 'Views/ProductsView.php';
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$model = new ProductsModel($db);
$controller = new ProductsController($model);
$view = new ProductsView();
$data = $controller->getAllProducts();
$view->render($data);
上面代码演示了你可能遇到的问题以及如何解决。通过确保模型、控制器和视图正常工作,以及正确的数据库连接,你就可以轻松地在 PHP POO MVC 应用程序中正确地显示表格数据。