Do I have to know the name of the column so to be able to insert data ? because I need to insert data using column number (first column is 1...)
2 Answers
Instead of using this :
insert into my_table (column1, column2)
values (value1, value2)
Just use that :
insert into my_table values (value1, value2)
i.e. don't specify the list of columns.
Of course, this will only work if you pass data for the columns in the order they are defined in the table, though.
1 Comment
if you have a table like (for example) :
CREATE TABLE test (
id INT(10),
field1 VARCHAR(16),
field2 TINYINT(1)
);
you can execute the query
INSERT INTO test VALUES (1, 'field1 value', 0);
The insert values must be in the same order as the declared columns. And as Galz mentioned it, you must set all fields, even the nullable or the auto incrementing ones. In fact, for the latter, you have to pass a null value.
For example, if id were to be a primary key set to "auto_increment", this query
INSERT INTO test VALUES (null, 'foo', 1);
SELECT * FROM test;
Would return
+----+--------------+--------+
| id | field1 | field2 |
+----+--------------+--------+
| 1 | field1 value | 0 |
| 2 | foo | 1 |
+----+--------------+--------+
On another subject, if you don't know beforehand what is the order of the fields, you can execute this query :
show columns from <table name>;
which, in this case would return
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id | int(10) | YES | | NULL | |
| field1 | varchar(16) | YES | | NULL | |
| field2 | tinyint(1) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
Thus telling you that id is the first field, field1 is the second, and field2 is third.