【问题标题】:PHP MVC passing form values to controller and modelPHP MVC 将表单值传递给控制器​​和模型
【发布时间】:2012-05-31 13:30:27
【问题描述】:

我正在尝试将 POST 值发送到控制器,然后将其传递给 PHP 中的模型,但我不知道该怎么做。

控制器的这一部分是看用户是否请求像?action=game这样的视图。这行得通。

但我正在尝试修改它以允许将$_POST 发送给它,然后发送给模型。

function __construct()
{
    if(isset($_GET['action']) && $_GET['action']!="" )
     {
         $url_view = str_replace("action/","",$_GET['action']);
         if(file_exists("views/" . $url_view . ".php" ))
         {
                $viewname = $url_view;
                $this->get_view($viewname . ".php");
          }
          else
          {
               $this->get_view('error.php');
          }
     } 
     else 
     {
         $this->get_view('home.php');
     }  
}

这就是我得到的。在注册表单页面,表单的action是?process=register,但是不起作用。

if(isset($_POST['process']) == 'register)
{
    $this->get_view('register.php')
}

Get_view 函数确定要与视图绑定的模型

function get_view($view_name)
{
    $method_name = str_replace(".php","",$view_name);
    if(method_exists($this->model,$method_name))
    {
       $data = $this->model->$method_name();
    } else {
      $data = $this->model->no_model();
    }
      $this->load->view($view_name,$data);
}

【问题讨论】:

  • 你在 if(isset($_POST['process']) == 'register) 中缺少一个结束单引号

标签: php model-view-controller model


【解决方案1】:

既然你的表单动作是?process=register,那么process仍然在$_GET超全局中。你可以做些什么来让它使用 post 是添加一个包含进程的隐藏输入字段。

有了这个:

<form method="post" action="script.php?process=register">

表单已发布到script.php?process=register,因此您拥有$_GET['process']不是 $_POST['process']

试试这个:

<form method="post" action="script.php">
<input type="hidden" name="process" action="register" />

拥有$_POST['process']。或者,您可以将“进程”保留在 GET 中,并将 if 语句切换为检查 $_GET 而不是 $_POST

【讨论】:

  • 谢谢。但我似乎无法让它工作。当我在注册表中发布到控制器时,即使我输入视图名称进行测试,它也会进入一个空白页面
  • 空白页意味着您的脚本中有一个致命错误,很可能是缺少其他人提到的'。如果你打开 PHP 设置 display_errors 你可以看到实际的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多