How can I pass input value from view to controller and model to fetch data correctly? Codeigniter

你离开我真会死。 提交于 2020-03-25 18:22:47

问题


I am trying to fetch a data that has the same id of my input hidden value.

I cannot fetch the id or input hidden value of the data

To start with, this is what I've done to make things clearer for me to debug things I made a hard coded form and a button to bring me to the page

In View - groups/index.php

As you can see I made the posts/index/1 which is a hard coded value but I can change that later easily that is not my problem

<?php echo form_open('posts/index/1') ?>

    <input type="hidden" name="txtGroup" value="1" />
    <button type="submit" class="btn btn-info"> Submit</button>

</form>

So after I made the form I will make a function in controller to fetch the posts/index

In Controller - Posts.php

public function index(){
    $this->load->view('templates/header');
    $this->load->view('teachers/posts/index');
    $this->load->view('templates/footer');   
}

And so I fetched the page. At this point, i can now go through /posts/index/1 and see my page

In my page posts/index.php I have a data and it is fetched through Ajax here it is

So I already fetched this data in posts/showPosts

showAllQuestions();

//Show all data
function showAllQuestions(){
    $.ajax({
        type: 'ajax',
        url: '<?php echo base_url() ?>posts/showPosts',
        async: false,
        dataType: 'json',
        success: function(data){
            var html = '';
            var i;
            var n=1;

            for(i=0; i<data.length; i++){
                html +='<div class="card">'+
                    '<div class="card-header" style="color:white; background-color:black">'+
                        '<h4><span class="iconify" data-icon="ant-design:info-circle-outlined" data-inline="false"></span> Question No. '+ n++ +'</h4>'+
                    '</div>'+
                    '<div class="card-body">'+
                        '<form>'+
                            '<div class="form-group">'+
                                '<label for="exampleFormControlTextarea1"><h5> <span class="iconify" data-icon="emojione:check-mark-button" data-inline="false"></span> </h5></label>'+
                                '<input type="text" value="'+data[i].question+'" class="form-control" disabled />'+
                            '</div>'+
                            '<hr>'+
                            '<a href="<?php echo base_url() ?>posts/edit/'+data[i].id+'" class="btn btn-info"><span class="iconify" data-icon="el:edit" data-inline="false"></span> </a>&nbsp;'+
                            '<a href="<?php echo base_url()?>posts/delete/'+data[i].id+'" class="btn btn-primary"><span class="iconify" data-icon="fa-solid:trash-alt" data-inline="false"></span></a>'+
                            //  '<a href="javascript:;" class="btn btn-info item-edit" data-id="'+data[i].id+'">Edit </a>&nbsp;'+
                        '</form>'+
                    '</div>'+
                '</div><br>';
            }

            $('#showdata').html(html);
        },
        error: function(){
            alert('Could not get Data from Database');
        }
});

}

In posts/showPosts - Posts.php, this is the controller

public function showPosts(){
    $result = $this->post_model->showPosts();
    echo json_encode($result);
}

Finally the Model to Determine if I fetched the correct ID depending on the data id I submit

Problem is the $id is null and I don't have a clue to start with, because I declare a hidden input value on the view page.

public function showPosts(){
    // Show questions and answers
    $id = $this->input->post('txtGroup');
    $this->db->select('*');
    $this->db->from('questions');
    $this->db->where('group_id', $id);
    $query = $this->db->get();
    return $result = $query->result_array();

}

回答1:


I am going to try to understand this question better than your previous one (which is now safe to delete since this is a better description of your issue).

In your groups/index.php view, you want to allow a user to navigate to the posts/index page and pass an integer as a single parameter (which is hard-coded by you, not entered by the user) -- I'll refer to it as $txtGroup for context. Because you are not performing a INSERT|UPDATE|DELETE operation, better practice is to send the data as a $_GET instead of $_POST. Because Codeigniter enables the passing of $_GET parameter as a slash-delimited extension of the url, I don't see any benefit in setting up a <form>.

Style your new hyperlink as a button using your preferred classes.

<a href="<?php echo base_url("posts/index/{$integer}"); ?>">Link to <?php echo $integer; ?></a>

This will send your data to the posts/index.php controller. This is where you should be accessing/extracting the $txtGroup value from the url.

Here's where I start to get foggy about what you need. If you want to pass the value to the teachers/posts/index view, then do so by passing an associative array as the second parameter when you load the view.

public function index($txtGroup) {
    $this->load->view('templates/header');
    // if you want to pass the value to THIS 
    $this->load->view('teachers/posts/index', ['txtGroup' => $txtGroup]);
    $this->load->view('templates/footer');   
}

If you are not interested in passing the $txtGroup to the view, then the only other reason to pass the value from groups/index.php to posts/index would be to modify a query and then pass dynamic data to the teachers/posts/index view (which you would need to supply when loading the view anyhow).

public function index($txtGroup) {
    $data['posts'] = $this->post_model->showPosts($txtGroup);
    $this->load->view('templates/header');
    $this->load->view('teachers/posts/index', $data);
    $this->load->view('templates/footer');   
}

In your model, use the passed argument.

public function showPosts($groupId) {
    return $this->db->get_where('questions', ['group_id' => $groupId])->result_array();
}

This way, you don't need to use an ajax call (which looks like you are unconditionally triggering in your view anyhow). Now Codeigniter will work its magic to transfer $data to your view whereby you can access the multidimensional result set as $posts (the variable is named by the first-level key that you assign it). Use a foreach() loop to iterate the rows of results and generate your html content -- all using server-side language.

<?php foreach ($posts as $index => $post) { ?> 
    <div class="card">
    // ... the rest of your content ...
<?php } ?>

As you design the new dynamic content using the above loop:

  • Use $index as your counter so that you don't have to manually increment.
  • DO NOT allow INSERT|UPDATE|DELETE operations to be triggered by $_GET events, this is not best practice. Those types of actions should only be initiated by $_POST submissions.


来源:https://stackoverflow.com/questions/60707881/how-can-i-pass-input-value-from-view-to-controller-and-model-to-fetch-data-corre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!