Codeigniter POST Form Submit Problems

2020-03-31 07:14发布

问题:

I just started learning CI and PHP and wanted to make a simple CRUD application.

I created a function to add a record, but when i submit the data in the form, Chrome downloads a file with no extension.

Controller

<?php

class Options extends CI_Controller{

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

}

function create()
{
    $data = array(

        'name' => $this->input->post('name'),
        'price' => $this->input->post('price'));

    $this->data_model->addItem($data);
    $this->index();
}

}

Model

<?php

class Data_model extends CI_Model {
function getAll() {
$q = $this->db->query("SELECT * FROM items");
if($q->num_rows() >0){
    foreach($q->result() as $row){
        $data[]=$row;
    }
}
return $data;
}

function addItem($data){
    $this->db->insert('items', $data);
    return;
}
}
?>

View

<html><head></head><body>
<style type="text/css">
label {display: block;}
</style>


<h2>Create</h2>
<?php echo form_open('options/create'); ?>

<p>
    <label for="name">Name</label><input type="text" name="name" id="name" />
</p>
<p>
    <label for="name">Price</label><input type="text" name="price" id="price" />
</p>

<p><input type="submit" value="Submit" /></p>

<?php echo form_close(); ?>

</body>
</html>

Is there something that i did wrong? No errors pop out. The form is created, but when i add data in the textboxes and click submit, the browser dowloands a "Create" file.

回答1:

Could it be that you don't need the last slash in that line?

<?php echo form_open('options/create/'); ?>


回答2:

i think you need to load form helper like

$this->load->helper(array('form', 'url'));

please let me know if you face any problem.



回答3:

Add $this->load->model('data_model'); to method before $this->data_model->addItem($data);