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
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 |
+----+----------+
Yes, leave it blank and MySQL gives it a value.
$query = "INSERT INTO comments (data_column_name) VALUES ('$comment')";
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.