简体   繁体   English

如何从数据库获取自动递增的ID值

[英]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. 我试图在codeigniter框架中的数据库中插入值,但出现此错误。

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 * ID int(10)自动递增主键

*Name:varchar(255) *名称:varchar(255)

*Email:varchar(255) *电子邮件:varchar(255)

*Designation:varchar(255) *名称:varchar(255)

*Contact:int(10) *联系人: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. 当我在控制器中使用print_r($ post)时,它不是打印字段的值而是在url中显示值。如果我错了,请告诉我。

Thanks in advance. 提前致谢。

Don't pass all post Request in model,make insert data array. 不要在模型中传递所有post Request,而是插入数据数组。

Check query by print last query. 通过打印最后一个查询来检查查询。

$this->db->last_query();

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. 我认为$ array没有所需格式的值,或者它为空。 So print the last insert query by using: 因此,使用以下命令打印最后一个插入查询:

$this->db->last_query();

and resolve the issue. 并解决问题。

On seeing your admin table description,i found that there is no column named '0'.Problem is in asked query.I suggest use this : 在查看您的管理表描述时,我发现没有名为'0'的列。问题出现在询问的查询中。我建议使用此命令:

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. 另外,如果该列标记为自动递增,则无需提供显式值。数据库将获取先前的值并自行递增。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM