【问题标题】:Cannot pass value to a controller function codeigniter无法将值传递给控制器​​函数 codeigniter
【发布时间】:2017-01-18 21:16:57
【问题描述】:

这是我的控制器代码

 public function create($postdate)
    {
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->helper('url');
      //  $postdate = $this->uri->segment(3);
        echo $postdate;



        $data['title'] = 'Hey there!';


        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('text', 'Text', 'required');

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

            $this->load->view('templates/header', $data);
            $this->load->view('pages/create',);
            $this->load->view('templates/footer');

        }
        else
        {   
            $this->news_model->set_news($postdate = 20160824);
            $this->load->view('pages/success');
        }
}

这是我的模型代码:

public function set_news($postdate)
{
$this->load->helper('url');


$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
    'title' => $this->input->post('title'),
    'slug' => $slug,
    'text' => $this->input->post('text'),
    'room_date' => $postdate

);

return $this->db->insert('news', $data);
}

但模型没有将值 $postdate 插入数据库。它插入默认值 20160824,其中控制器中的回显显示作为参数传递的值,即我想在数据库中插入的(正确的)值。

【问题讨论】:

  • room_date 列的数据类型是?
  • 我是 codeignitor 的新手,因此我将表单提交给 create() 本身。这导致了问题。解决了。!

标签: php codeigniter codeigniter-2 codeigniter-3


【解决方案1】:

您不会在函数调用中提供默认值。而是在函数定义中提供默认值。

SanketR 已正确回答您的问题。我想说清楚。

在你的控制器中:

您正在将$postdate 的值更改为20160824。这不是预期的行为。 改变这个:

$this->news_model->set_news($postdate = 20160824);

$this->news_model->set_news($postdate);

并在您的模型中,将函数头更改为:

public function set_news($postdate = 20160824)

如果控制器的函数调用中未提供该变量,这将为$postdate 设置默认值。

【讨论】:

    【解决方案2】:

    你做错了。正确的方法是

    public function set_news($postdate = 20160824)
    {
    $this->load->helper('url');
    
    
    $slug = url_title($this->input->post('title'), 'dash', TRUE);
    $data = array(
        'title' => $this->input->post('title'),
        'slug' => $slug,
        'text' => $this->input->post('text'),
        'room_date' => $postdate
    
    );
    
    return $this->db->insert('news', $data);
    }
    

    在你的控制器中

    $this->news_model->set_news($postdate);

    【讨论】:

    • 发生数据库错误 错误编号:1048 列 'room_date' 不能为空 INSERT INTO news (title, slug, text, room_date) VALUES ('just for fun', 'just-for-fun', 'lijo', NULL) 文件名:C:/wamp/www/system/database/DB_driver.php 行号:691
    • 这意味着您没有在控制器内收到$postdate 的值。可以查一下吗?
    • 当我在控制器内回显时,它会回显正确的值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    相关资源
    最近更新 更多