如何将我的模型添加到控制器中以显示下拉值? 我得到的错误:为foreach()提供的参数无效 我没有使用任何框架。只是本机的PHP。我是MVC和PHP的新手,请帮忙!
我的控制器:
<?php
class Index extends Controller {
function __construct(){
parent::__construct();
}
function index(){
$landArray = $this->model->fetchData();
$this->view->render('index/index');
var_dump($landArray); // display all row in database
}
}
型号:
<?php
class Index_Model extends Model {
function __construct(){
parent::__construct();
}
function fetchData(){
$selectIsland = $this->connection->prepare("SELECT island_id, island
from island" );
$selectIsland->setFetchMode(PDO::FETCH_ASSOC);
$selectIsland->execute();
$islandResult = $selectIsland->fetchAll();
return $islandResult;
}
}
查看:
<select>
<option value="">--- Select Island---</option>
<?php
foreach($islandResult as $row){
echo '<option value="'.$row['island_id'].'">'.$row['island'].'</option>';
endforeach
}?>
</select>
这是我的库视图和渲染方法。
<?php
class View {
function __construct(){
}
public function render($name, $noInclude = false, $landArray){
if($noInclude == true){
require 'views/'.$name.'.php';
}else{
require 'views/header.php';
require 'views/'.$name.'.php';
require 'views/foother.php';
}
}
}
}
答案 0 :(得分:1)
您从未调用模型的fetchData()
方法。在MVC控制器控制一切。在您的控制器中,您必须从模型中调用方法。然后将它们传递给您的视图文件。
<?php
class Index extends Controller {
function __construct(){
parent::__construct();
}
function index(){
$landArray = $this->model->fetchData();
$this->view->render('index/index', false, array('islandResult' => $landArray)); // as we are sending param to view and render accept that as 3rd param so we need to specify the 2nd param too!
}
}
Model:
<?php
class Index_Model extends Model {
function __construct(){
parent::__construct();
}
function fetchData(){
$selectIsland = $this->connection->prepare("SELECT island_id, island
from island" );
$selectIsland->execute();
$islandResult = $selectIsland->fetchAll();
return $islandResult; //if you need something to pass to view from db first you have to pass it to controller from model
}
}
View:
<select>
<option value="">--- Select Island---</option>
<?php
foreach($islandResult as $row){
echo '<option value="'.$row['island_id'].'">'.$row['island'].'</option>';
}
?>
</select>
View/Render Library Method:
class View {
function __construct(){
}
public function render($name, $noInclude = false, $arrayParam = array()){ //look closely...here i've made 3rd parameter as default argument so that your other codes which don't need to send param to view works smoothly.
if(count($arrayParam) > 0){
extract($arrayParam);
}
if($noInclude == true){
require 'views/'.$name.'.php';
}else{
require 'views/header.php';
require 'views/'.$name.'.php';
require 'views/foother.php';
}
}
}
现在,您将能够使用从控制器发送的视图中的参数。你在控制器中的数组键传递的任何内容都可以在视图中用作变量。
N.B:从代码中查看我的评论。