user6891871
user6891871

Reputation: 174

How to get auto incremented id value from database

I am trying to insert the value in the database in codeigniter framework but getting this error.

A Database Error Occurred

Error Number: 1054

Unknown column '0' in 'field list'

INSERT INTO `admin_table` (`0`) VALUES ('')

Filename: C:\xampp\htdocs\CI\system\database\DB_driver.php

Line Number: 331

Admin_table

*ID int(10) auto-increment primary key

*Name:varchar(255)

*Email:varchar(255)

*Designation:varchar(255)

*Contact:int(10)

View:

<form>
<input type="hidden" name="ID">
<legend>Add Data</legend>
    <label>Name</label>
      <?php echo form_input(['name'=> 'Name','placeholder'=>'Name',]);?>
    <label>Email</label>
      <?php echo form_input(['name'=> 'Email','placeholder'=>'Email']);?>
    <label>Designation</label>
      <?php echo form_input(['name'=> 'Designation','placeholder'=>'Designation']);?>
    <label>Contact</label>
      <?php echo form_input(['name'=> 'Contact','placeholder'=>'Contact']);?>
    <?php echo form_reset(['name'=>'Reset','value'=>'Reset']); ?>
    <?php echo form_submit(['name'=>'submit','value'=>'Add']) ?>
</form>

Controller:

      $this->load->library('form_validation');
      $post= $this->input->post();
      $this->load->model('model');
      if( $this->model->add_data($post)){
          //insert succesfully
      }
      else{
         //insert failed
      }

Model:

    $this->db->insert('admin_table',$array);
    $last_id=$this->db->insert_id();
    return $last_id;

And when i use print_r($post) in controller,it's not printing the values of the field but show the value in url.Where i am wrong please tell me.

Thanks in advance.

Upvotes: 0

Views: 446

Answers (3)

Bharat Dangar
Bharat Dangar

Reputation: 527

Don't pass all post Request in model,make insert data array.

Check query by print last query.

$this->db->last_query();

Upvotes: 1

Shagun Bhatt
Shagun Bhatt

Reputation: 96

On seeing your admin table description,i found that there is no column named '0'.Problem is in asked query.I suggest use this :

INSERT INTO `admin_table` (`id`) VALUES ('1')

Also,if the column is marked auto increment then there is no need to provide explicit value.Database will fetch the previous value and increment it by itself.

Upvotes: 0

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

The problem arises from the following line:

$this->db->insert('admin_table',$array);

I think the $array do not have the values in required format or it is empty. So print the last insert query by using:

$this->db->last_query();

and resolve the issue.

Upvotes: 1

Related Questions