php 如何使用 CodeIgniter 处理表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2279282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:50:37  来源:igfitidea点击:

How to process a form with CodeIgniter

phpcodeigniter

提问by Ramesh

I am new to CodeIgniter. I need to process a form. I have a form.html page in view

我是 CodeIgniter 的新手。我需要处理一个表格。我有一个 form.html 页面在视图中

<html>
  <head>
    <title>Search</title>
  </head>
  <body>
    <form action="search">
      <input type="text" name="search" value="" size="50" />
      <div>
        <input type="submit" value="Submit" />
      </div>
    </form>
  </body>
</html>

and form controller

和表单控制器

class Form extends Controller {

  function Form() {
    parent::Controller();   
  }

  function index() {    
    $this->load->view('form');
  }

}

and I have an view file search.php but when it is processed it shows page not found...

我有一个视图文件 search.php 但是当它被处理时它显示页面未找到...

回答by Sean Vieira

In M.odel V.iew C.ontroller setups like CodeIgniter the Views are user interface elements. They should not be parsing results.

在像 CodeIgniter 这样的M.odel V.iew C.ontroller 设置中,视图是用户界面元素。他们不应该解析结果。

If I am not mistaken, what you are looking to do is pass data from www.yoursite.com/index.php/formto www.yoursite.com/index.php/search

如果我没记错的话,您要做的是将数据从www.yoursite.com/index.php/formwww.yoursite.com/index.php/search

In unstructured php you might have a form.htmlwith a form action of search.php. A user would navigate to yoursite.com/form.html, which would call yoursite.com/search.php, which might redirect to yoursite.com/results.php.

在非结构化的 php 中,您可能有一个form.html带有search.php. 用户将导航到yoursite.com/form.html,调用yoursite.com/search.php,然后重定向到yoursite.com/results.php

In CodeIgniter (and, as far as I understand it, in any MVC system, regardless of language) your Controller, Formcalls a function which loads the form.htmlViewinto itselfand then runs it. The Viewgenerates the code (generally HTML, but not necessarily) which the user interacts with. When the user makes a request that the View cannot handle (requests for more data or another page) it passes that request back to the Controller, which loads in more data or another View.

在笨(和,据我了解,在任何MVC系统,无论何种语言的)的控制器Form调用一个函数,它加载form.html查看到自身,然后运行它。该视图生成代码(一般HTML,但不是必须)用户与之交互以。当用户发出视图无法处理的请求(请求更多数据或其他页面)时,它会将请求传递回控制器,控制器加载更多数据或另一个视图。

In other words, the View determines how the data is going to be displayed. The Controller maps requests to Views.

换句话说,视图决定了数据将如何显示。控制器将请求映射到视图。

It gets slightly more complicated when you want to have complex and / or changing data displayed in a view. In order to maintain the separation of concernsthat MVC requires CodeIgniter also provides you with Models.

当您想要在视图中显示复杂和/或更改的数据时,它会变得稍微复杂一些。为了保持关注点分离,MVC 需要 CodeIgniter 还为您提供了Models

Models are responsible for the most difficult part of any web application - managing data flow. They contain methods to read data, write data, and most importantly, methods for ensuring data integrity. In other words Models should:

模型负责任何 Web 应用程序中最困难的部分 - 管理数据流。它们包含读取数据、写入数据的方法,最重要的是,包含确保数据完整性的方法。换句话说,模型应该:

  • Ensure that the data is in the correct format.
  • Ensure that the data contains nothing (malicious or otherwise) that could break the environment it is destined for.
  • Possess methods for C.reating, R.eading, U.pdating, and D.eleting data within the above constraints.
  • 确保数据格式正确。
  • 确保数据不包含任何可能破坏其预定环境的内容(恶意或其他)。
  • 在上述约束内拥有C.reating、R.eading、U.pdating 和D.eleting 数据的方法。

Akeloshas a good graphic laying out the components of MVC:

Akelos有一个很好的图表,展示了 MVC 的组件:

Request - Response
(source: akelos.org)

请求 - 响应
(来源:akelos.org

That being said, the simplest (read "easiest", not "most expandable") way to accomplish what you want to do is:

话虽如此,完成您想做的事情的最简单(阅读“最简单”,而不是“最可扩展”)方法是:

function Form()
{
    parent::Controller();   
}

function index()
{   
        $this->load->view('form');
}

function search()
{
        $term = $this->input->post('search');
        /*
            In order for this to work you will need to 
            change the method on your form.
            (Since you do not specify a method in your form, 
            it will default to the *get* method -- and CodeIgniter
            destroys the $_GET variable unless you change its 
            default settings.)

            The *action* your form needs to have is
            index.php/form/search/
        */

        // Operate on your search data here.
        // One possible way to do this:
        $this->load->model('search_model');
        $results_from_search = $this->search->find_data($term);

        // Make sure your model properly escapes incoming data.
        $this->load->view('results', $results_from_search);
}

回答by Donny Kurnia

View file is useless without the controller to load and displaying it. You must create a controller to receive the form data, process it, then displaying the process result.

没有控制器加载和显示视图文件是没有用的。您必须创建一个控制器来接收表单数据,对其进行处理,然后显示处理结果。

You can use a form helper to set the form open tags, also the close tags:

您可以使用表单助手来设置表单的打开标签,以及关闭标签:

<?php echo form_open('form/search'); ?>
<input type="text" name="search" value="" size="50" />
<div><input type="submit" value="Submit" /></div>
<?php echo form_close(); ?>

Without using form helper, you can still write it this way:

不使用表单助手,你仍然可以这样写:

<form action="<?php echo site_url('form/search'); ?>">

Then add the searchmethod into formcontroller:

然后将search方法添加到form控制器中:

function search()
{
  //get form field
  $search = $this->input->post('search');
  // do stuffs here
  //...
}

Remember that CI only help you with the basic code organization and provide a helpful library and helper. But you still need to write the algorithm of the process in your site.

请记住,CI 仅帮助您进行基本的代码组织,并提供有用的库和帮助程序。但是您仍然需要在您的站点中编写流程的算法。

Don't forget to read the included user guide in the downloaded codeigniter package. You can learn many stuffs from the example in there. Don't hesitate to ask things you don't know here, many member of stackoverflow will help you.

不要忘记阅读下载的 codeigniter 包中包含的用户指南。你可以从那里的例子中学到很多东西。不要犹豫,在这里问你不知道的事情,stackoverflow 的许多成员会帮助你。

回答by cgwCode

This is form validation and submit in controllerMy whole controller class

这是表单验证并在控制器中提交我的整个控制器类

    class MY_Controller extends CI_Controller {

        function __construct()
        {
            parent::__construct();

            $this->load->library(array('session','form_validation'));
            $this->load->helper(array('form', 'url', 'date'));

            //$this->load->config('app', TRUE);

            //$this->data['app'] = $this->config->item('app');


            }
    }

    <?php

    if (!defined('BASEPATH'))
        exit('No direct script access allowed');

    class Article extends MY_Controller {

        function __construct() {
            parent::__construct();
            $this->load->model('article_model');
        }

        public function index() {

            $data['allArticles']    =   $this->article_model->getAll(); 

            $data['content']        =   $this->load->view('article', $data, true);
            $this->load->view('layout', $data);

        }

        public function displayAll() {

            $data['allArticles']    =   $this->article_model->getAll(); 

            $data['content']        =   $this->load->view('displayAllArticles', $data, true);
            $this->load->view('layout', $data);

        }

        public function displayArticle($id) {

            $data['article']        =   $this->article_model->read($id); 

            $data['articleId']      =   $id;

            $data['comment']        =   $this->load->view('addComment', $data, true);

            $data['content']        =   $this->load->view('displayArticle', $data, true);


            $this->load->view('layout', $data);

        }

        public function add() {

            $this->form_validation->set_message('required', '%s is required');
            $this->form_validation->set_rules('title', 'Title', 'required|xss_clean');
            $this->form_validation->set_rules('description', 'Description type', 'required|xss_clean');

            $this->form_validation->set_error_delimiters('<p class="alert alert-danger"><a class="close" data-dismiss="alert" href="#">&times;</a>', '</p>');


            if ($this->form_validation->run() == TRUE) {

                 $article = array(
                        'title'         => $this->input->post('title'),
                        'description'   => $this->input->post('description'),
                        'created'       => date("Y-m-d H:i:s")
                  );

                 $this->article_model->create($article);

                 redirect('article', 'refresh');


            } else {

                 $data['article'] = array(
                    'title'         => $this->input->post('title'),
                    'description'   => $this->input->post('description'),
                );

                $data['message'] = validation_errors();

                $data['content'] = $this->load->view('addArticle', $data, true);
                $this->load->view('layout', $data);
            }
        }

    }

We can use normal html form like this.

我们可以像这样使用普通的 html 表单。

            <?php echo $message; ?>

           <form method="post" action="article/add" id="article" >
                <div class="form-group">
                    <label for="title">Article Title</label>
                    <input type="text" class="form-control" id="title" name="title" value="<?php echo $article['title']; ?>" >
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control" rows="13" name="description" id="description"><?php echo $article['description']; ?></textarea>
                </div>

                <button type="submit" class="btn btn-default">Submit</button>
            </form>     
        </div>
    </div>

回答by slav

replace this <form action="search">with <?php echo form_open('form/search');?>and autoload.php file add $autoload['helper'] = array('form');

将其替换<form action="search"><?php echo form_open('form/search');?>autoload.php 文件添加$autoload['helper'] = array('form');

and then file dont use file search.php just add your search.php code into your Controller file like here

然后文件不要使用文件 search.php 只需将您的 search.php 代码添加到您的控制器文件中,如下所示

class Form extends Controller {

  function Form() {
    parent::Controller();   
  }

  function index() {    
    $this->load->view('form');
  }

function search(){
//your code here
}
}

回答by Shane

Try using the codeigniter 'site_url' in your action to make sure you are pointing to the right place. The action in your example would have gone to the 'search' controller rather than the 'form' controller.

尝试在您的操作中使用 codeigniter 'site_url' 以确保您指向正确的位置。您示例中的操作将转到“搜索”控制器而不是“表单”控制器。

<html>
<head>
<title>Search</title>
</head>
<body>
<form action="<?= site_url('form/process_search') ?>">
<input type="text" name="search" value="" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>

index is only used in your controller when nothing else is passed.. So in the case of my example above you would want something like this:

index 仅在没有传递任何其他内容时在您的控制器中使用。因此,在我上面的示例中,您需要这样的东西:

function Form()
{
    parent::Controller();   
}

function process_search()
{   

     print "<pre>";

     print_r($_POST);

     print "</pre>";
}

回答by Yada

Nettuts has a great tutorial for CodeIgniter for Login form. Follow the screencast and it will clear up your questions.

Nettuts 有一个很棒的 CodeIgniter 登录表单教程。按照截屏视频进行操作,它会解决您的问题。

http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-6-login/

http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-6-login/