Search code examples
mysqlauto-increment

Get the auto increment-primary key column programatically


witch is the auto increment field in a mysql table?

I have a table structure, for example: table name is my_table and the fields are my_id, my_name, my_blah.. The one of fields is an auto incremented primary key. Witch is it?

How can I get the name of auto increment field on this table with a php code and/or a mysql query?


Solution

  • You can use the MySQL SHOW COLUMNS query to retrieve information about the columns in a table:

    mysql> SHOW COLUMNS FROM `test`;
    +----------+--------------+------+-----+---------+----------------+
    | Field    | Type         | Null | Key | Default | Extra          |
    +----------+--------------+------+-----+---------+----------------+
    | id       | int(11)      | NO   | PRI | NULL    | auto_increment |
    | col1     | varchar(100) | YES  |     | NULL    |                |
    | col2     | int(11)      | YES  |     | NULL    |                |
    +----------+--------------+------+-----+---------+----------------+
    

    The extra column will contain auto_increment for the primary key field.