CodeIgniter Forums
Add table and fieldname - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forum-5.html)
+--- Forum: General Help (https://forum.codeigniter.com/forum-24.html)
+--- Thread: Add table and fieldname (/thread-72822.html)



Add table and fieldname - jaysondotp - 02-15-2019

Hi. im going to add database table and field and of course the field type,auto_increment and so on..  and  
may i ask what what is wrong with this?

PHP Code:
$tblname $this->input->post('tblname');
        
$fldname $this->input->post('fld_name[]');
        
                
$fldtype $this->input->post('fld_type');
                
$fldauth $this->input->post('fld_aut');
                
$fldlgth $this->input->post('fld_lgth');
                
        for(
$i 0$i count($fldname); $i++)    
            {
                
$insert = [[$fldname] => ['type' => $fldtype,
                            
'auto_increment' => $fldauth,
                            
'constraint' => $fldlgth,
                            
'null' =>TRUE]];
                
                
$this->dbforge->add_field($insert);
                
$this->dbforge->add_key($fldnameTRUE);
                
$this->dbforge->create_table($tblnameTRUE);
            } 

Thanks


RE: Add table and fieldname - Wouter60 - 02-16-2019

Quote:may i ask what what is wrong with this?

You forgot the square brackets in the field attribute inputs. So all fields will have the same settings for field type, auto increment and length.
Then, in the for next loop for the fields, you make dbforge create the same table over and over again.

The right approach is:
1. Fetch the table name
2. In the for next loop (why not foreach … ?) create the array with all fields and their attributes
3. After the loop, let dbforge create the table.

PHP Code:
$tblname $this->input->post('tblname');
$fieldnames $this->input->post('fld_name[]');
$fieldtypes $this->input->post('fld_type[]');
$fieldauths $this->input->post('fld_aut[]');
$fieldlengths $this->input->post('fld_lgth[]');

$fields = array();

foreach (
$fieldnames as $index=>$fieldname) {
 
   $fields[] = array(
 
       $fieldname => array(
 
           'type' => $fieldtypes[$index],
 
           'constraint' => $fieldlenghts[$index],
 
           'auto_incremenet' => $fieldauths[$index],
 
       ), 
 
   );
}

$this->dbforge->add_field($fields);
$this->dbforge->create_table($tblname); 



RE: Add table and fieldname - InsiteFX - 02-16-2019

I think he will also have a problem with the auto_increment field.