0

Im trying use "$this->input->post();" of Codeigniter to do not need specify each field in my form. But im getting troubles when try insert into Database.

Look my controller:

public function cadastrar(){
        $var = $this->input->post(null, TRUE);
        $this->load->model('m_clientes');
        $this->m_clientes->inserir($var);
}

My controller is simplified here because i know how to handle database in codeigniter. The result of this post was:

  Array ( [nome] => Raphael [sobrenome] => Schubert [cpf] => 893.528.432-89 [rg] => 4529875231908472 [telefone] => (53) 2980-5792 [celular] => (53) 9 2180-7529 [rua] => Israel de Almeida [numero] => 859 [cep] => 88.312-000 [bairro] => São Vicente [cidade] => ITAJAÍ [estado] => Santa Catarina [email] => [email protected] [tipo] => pf [cnpj] => 34.827.481/2834-78 [inscricaoestadual] => 34120489032814930128 [razaosocial] => Teste [nomefantasia] => Disney [dataaberturaempresa] => 10/21/15 [proprietario] => Marcos Aurelio )

I normaly use this way to insert:

$data = array(
'user_name' => $this->input->post('user_name',TRUE);
'user_phone' => $this->input->post('user_phone',TRUE);
'user_role' => $this->input->post('user_role',TRUE);
);
$this->name_of_model->inserir($data);

And works...

But i was trying to use just $this->input->post(); to get all fields from form. Because my actualy application will have hundreds of fields and i was trying to do not write each line.

So my model actually was:

   public function inserir($var){
        if($var!=NULL):
            print_r($var);
            $this->db->insert('tb_usuarios',$var);
        endif;
    }

But i`m getting and error saying:

Message: Undefined property: Clientes::$db and Message: Call to a member function insert() on null

My table name is: "tb_usuarios" I changed all fields in database to accept NULL to see if i`m get some field name wrong... but not work...

Any tips??

5 Answers 5

1

There is no need to catch the POST var inside $var. You can see POST variable inside the model very well. So all you need to do in the controller is:

public function cadastrar(){
    $this->load->model('m_clientes');
    $this->m_clientes->inserir();
}

,and inside your model:

public function inserir(){
    if( count($this->input->post()) > 0):
        $this->db->insert('tb_usuarios',$this->input->post());
    endif;
}

The fields names in your form must correspond to the column names inside your table. The message Message: Call to a member function insert() on null means you forgot to load the database library, just like remiheens said.

But my advice is, to use form validation for your fields, so you may be sure all necessary fields are completed using the required data format for each one of them. Although this may require allot of coding, there is no other safe way from errors on database operations. You cannot trust the user to insert the data correctly, that's why you need form validation.

Sign up to request clarification or add additional context in comments.

1 Comment

The controller method should be passing all required data into the model method. The model method should not be directly accessing any superglobal data. If inserting new rows in the database which generates an auto-incremented primary id, return the generated id as proof of success and to facilitate logging processes.
1

In here $var = $this->input->post(null, TRUE); you use null. null is not valid input name. name = ''

and this will works $this->input->post('user_name',TRUE);

Because it has input tag name (name = 'user_name').

We use ,TRUE) next to input post field to allows XSS Protection

$var = $this->input->post(null, TRUE); is wrong

while you trying this, it shows

Message: Undefined property: Clientes::$db and Message: Call to a member function insert() on null.

will not work

public function cadastrar(){
        $var = $this->input->post(null, TRUE);//will never give valid response 
        $this->load->model('m_clientes');
        $this->m_clientes->inserir($var);
}

Works well

public function cadastrar(){
        $this->load->model('m_clientes');
        $data = array(
        'user_name' => $this->input->post('user_name',TRUE);
        'user_phone' => $this->input->post('user_phone',TRUE);
        'user_role' => $this->input->post('user_role',TRUE);
        );
        $this->name_of_model->inserir($data);
        $this->load->model('m_clientes');
}

1 Comment

The second loading of m_clientes is pointless. name_of_model can obviously be written for this example as m_clientes.
0

This is because your database isn't loaded into codeigniter instance. ($this->db) Just try to autoload "database" library (config/autoload.php) or load/connect your database in your model with :

$this->load->database();

Don't forget to edit your config/database.php ;)

1 Comment

Tanks for answer... i use autoload function of CI to load Database.. because my entire application use database... so do not need to load in controller... tanks anyway!
0

I handle hundreds of fields everytime but I also validate basically each one. I always do this:

$customer['name']     = $this->input->post('customer_name');
$customer['age']      = $this->input->post('customer_age');
$customer['country']  = $this->input->post('customer_country');
$customer['city']     = $this->input->post('customer_city');

// validations
if(isAgeValid($customer['age']) == FALSE)
{
   echo 'Hold on, your age...hmm check it out!';
   return;
}

$this->customers_model->add($customer);

The function that handles the insertion only has this:

public function add($data)
{
    $data = $this->security->xss_clean($data);
    $this->db->insert('customers', $data);

    return $this->db->insert_id();
}

Pretty clean and simple. Now, if you don't want to validate the fields or just want to validate some of them and want to insert the others without validation this is what I purpose based on the previous code:

// validations..
if(isAgeValid());

$customer = array();

foreach($_POST as $key => $value)
   $customer[$key] = $value;

$this->customers_model->add($customer);

2 Comments

why don't you use CI form validation library? It's even cleaner then that.
I do enjoy lots of things by using the CI framework, but validating input by the form library isn't one.
-1
$data = array(
'user_name' => $this->input->post('user_name');
'user_phone' => $this->input->post('user_phone');
'user_role' => $this->input->post('user_role');
);

$this->load->model('name_of_model');
$this->name_of_model->inserir($data);


Model:

public function inserir($data)
{
$this->db->insert('***', $data);
if ($this->db->affected_rows() > 0) {
        return true;
    }

 }          

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.