proper way of inserting data with id as auto-increment in mysqli

后端 未结 3 904
予麋鹿
予麋鹿 2020-12-21 06:20

can someone please verify the proper way of inserting data using MYSQLI?

i need to insert comment data into the table with ID set as auto-increment. do i just leave

相关标签:
3条回答
  • 2020-12-21 07:04

    For an auto-increment column, you can omit it from the column list, and it will generate a new auto-increment value. You do this as @YourCommonSense showed, by specifying all columns except for the auto-increment column:

    INSERT INTO comments (comment) VALUES ('comment')
    

    For what it's worth, MySQL does the same thing if you specify 0 or NULL or DEFAULT for the auto-increment column.

    Below is an example test:

    mysql> select version();
    +---------------+
    | version()     |
    +---------------+
    | 5.6.13-56-log |
    +---------------+
    
    mysql> select @@sql_mode;
    +--------------------------------------------+
    | @@sql_mode                                 |
    +--------------------------------------------+
    | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION |
    +--------------------------------------------+
    
    mysql> insert into comments values (0, 'comment1');
    Query OK, 1 row affected (0.00 sec)
    
    mysql> insert into comments values (null, 'comment2');
    Query OK, 1 row affected (0.00 sec)
    
    mysql> insert into comments values (default, 'comment3');
    Query OK, 1 row affected (0.00 sec)
    
    mysql> select * from comments;
    +----+----------+
    | id | comment  |
    +----+----------+
    |  1 | comment1 |
    |  2 | comment2 |
    |  3 | comment3 |
    +----+----------+
    
    0 讨论(0)
  • 2020-12-21 07:14

    Yes, leave it blank and MySQL gives it a value.

    $query = "INSERT INTO comments (data_column_name) VALUES ('$comment')";
    
    0 讨论(0)
  • 2020-12-21 07:23

    A proper way would be either omit value, or assign NULL to it.
    While empty string which is used in your example, is not a valid value and in strict mode it will issue a warning.

    INSERT INTO comments VALUES (NULL, 'comment')
    INSERT INTO comments (comment) VALUES ('comment')
    

    are all valid.

    0 讨论(0)
提交回复
热议问题