简体   繁体   中英

variable is losing the id when form is submitted

I am using codeigniter and I am trying to update news articles, I am getting the id from the url when the user clicks the update button, by using id = $this->uri->segment(3);, when the update button is clicked it loads a view called update. the problem I am encountering is the variable is not passing my id to the model because when I submit the form the id is no longer stored in the $id variable. any help would be mostly appreciated.

news controller

public function update() {


    $id = $this->uri->segment(3);
    $this->load->helper('form');
    $this->load->library('form_validation');

    $data['title'] = 'Update a news item';
    $this->load->view('news/update');
    $this->form_validation->set_rules('title', 'Title', 'required');
    $this->form_validation->set_rules('text', 'Text', 'required');

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


    $this->News_model->update($id);
    redirect('News/index');

    }


} 

news model

 public function update($id) {

        $slug = url_title($this->input->post('title'), 'dash', TRUE);


         $data = array(
        'title' => $this->input->post('title'),
        'slug' => $slug,
        'text' => $this->input->post('text')
    );



     $this->db->where('id',$id);
     $this->db->update('news',$data);

 }

main news page

    <h1><?php echo $title; ?></h1>
    <p class="lead"><a href="<?php echo site_url('News/create'); ?>">Create Article</a></p>;
  </div>


 <?php foreach ($news as $news_item): ?>
 <h3><?php echo $news_item['title']; ?></h3>

  <div class="row">
    <div class="col-xs-12 col-sm-6 col-lg-6"> <?php echo $news_item['text']; ?></div>
    <div class="col-xs-6 col-lg-2"><p><a href="<?php echo site_url('news/'.$news_item['id']); ?>">View article</a></p></div>
    <div class="col-xs-6 col-lg-2"><p><a href="<?php echo site_url('News/update/'.$news_item['id']); ?>">update</a></p></div>
     <div class="col-xs-12 col-sm-6 col-lg-2"><p><a href="<?php echo site_url('News/delete/'.$news_item['id']); ?>">Delete article</a></p></div>
    </div>

 <?php endforeach; ?>

Why are you using ->uri to get the URI segments? First segment is the controller name, second is the method name, any further segments, are passed into the method as input parameters. So redefine your update method to include the $id as the input parameter. And check immediately if the $id is set. If it's not, then your URL is not correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM