I'm new to codeigniter and there is a question i want to ask about inserting information in my mysql database.I have a home.php controller, where from i can get data from my database via a model I have made, bud the opposite thing -> inserting data in my db, i can't do it. So, i have a controller function -> insertData, which calls a VIEW -> viewInserts, and in this VIEW i have a from where I want to take the insert data and redirect it to my database. Can you help me about it. I want to make a MODEL which will trigger this action and pass it to the VIEW but am confused right now about the logic. Does the insert_batch() function will do it ?
Very simple
1. call view from controller
2. submit form
3. save data in db or send to data in model here can add data
1. Controller test.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class test extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
}
public function add()
{
$this->load->view('test');
}
public function save()
{
//write form validation
$this->form_validation->set_rules('fname','First Name','required|min_length[3]');
$this->form_validation->set_rules('lname','Last Name','required|min_length[3]');
if ($this->form_validation->run() == FALSE) {
//error in validation redirect to form
$this->add();
}
else {
$fname = $this->input->post('fname');
$lname = $this->input->post('lname');
$insertData = array ('fname'=> $fname,
'lname'=>$lname );
//save data using model function or save data directly here
/*
$this->load->model('test_model');
$this->test_model->insertRecord($insertData);
*/
$this->db->insert('testtbl',$insertData);
redirect(base_url().'add');
}
}
}?>
2. view test.php
<form id="testFrm" name="testFrm" action="<?php base_url().?>test/save" method="post">
<input type="text" id="fname" name="fname" value="<?php set_value('fname');?>" >
<input type="text" id="lname" name="lname" value="<?php set_value('lname');?>" >
<input type="submit" id="subBtn" name="subBtn" value="Save" >
</form>
3. Model test_model.php
<?php
if (!defined('BASEPATH'))exit('No direct script access allowed');
class Test_Model extends CI_Model {
function insertRecord($insertData) {
$this->db->insert('testtbl',$insertData);
}
}
?>