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?
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With