How does autoincrement work in PHP when inserting data into a SQL database?
When inserting data into a SQL database with an autoincrement primary key column, you do not need to specify a value for that column. The database will automatically generate a unique value for each new record. Simply omit the autoincrement column from the INSERT query and provide values for the other columns.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert data into the table with an autoincrement primary key column
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close the connection
$conn->close();
?>