Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a row to a table with auto_increment column

I'm working on a table that has 4 columns and the first one is an auto incrementing integer called id.

If I'm going to insert into this table using mysqli prepared statements I keep having trouble inserting a query that works. Using phpMyAdmin It tells me to give it NULL. I've tried this:

$query = "INSERT INTO tbl (id, col2, col3, col4) VALUES ('NULL', ?, ?, ?)";
$stmt -> bind_param("ssi", $col2, $col3, $col4)

And this

$query = "INSERT INTO tbl (id, col2, col3, col4) VALUES (NULL, ?, ?, ?)";
$stmt -> bind_param("ssi", $col2, $col3, $col4)

And only give bind_param 3 arguments (the last 3). Neither of those work. I also tried this:

$null = NULL;
$query = "INSERT INTO tbl (id, col2, col3, col4) VALUES (?, ?, ?, ?)";
$stmt -> bind_param("issi", $null, $col2, $col3, $col4);

None of these work. Is there a standardized way of inserting into this type of table?

like image 762
fdfdsfsdfsdfds Avatar asked Feb 09 '10 06:02

fdfdsfsdfsdfds


People also ask

How do I add an auto increment to an existing column?

Here's the syntax of ALTER TABLE statement, ALTER TABLE table_name MODIFY column_name INT NOT NULL AUTO_INCREMENT PRIMARY KEY; In the above statement, you need to specify the table_name and column_name. Here's the SQL statement to add AUTO INCREMENT constraint to id column.

Can you set auto increment?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How do you auto increment a table?

You can also make an auto increment in SQL to start from another value with the following syntax: ALTER TABLE table_name AUTO_INCREMENT = start_value; In the syntax above: start_value: It is the value from where you want to begin the numbering.


2 Answers

Just skip the id field, MySQL will fill it automatically:

$query = "INSERT INTO tbl (col2, col3, col4) VALUES (?, ?, ?)";
$stmt->bind_param("ssi", $col2, $col3, $col4)
like image 101
Tatu Ulmanen Avatar answered Sep 17 '22 05:09

Tatu Ulmanen


If the id field is the auto_increment, then just don't specify it in your insert query :

$query = "INSERT INTO tbl (col2, col3, col4) VALUES (?, ?, ?)";

And, of course, don't try to bind any parameter to it ;-)


As it's generated by MySQL, there is no need to pass that column.

like image 38
Pascal MARTIN Avatar answered Sep 18 '22 05:09

Pascal MARTIN