What are some potential pitfalls of manually incrementing IDs in PHP when inserting data into a database?
Manually incrementing IDs in PHP when inserting data into a database can lead to potential issues such as duplicate IDs, gaps in the sequence, and concurrency problems in a multi-user environment. To solve this, it is recommended to use auto-incrementing primary keys in the database to ensure unique and sequential IDs are generated automatically.
// Example of inserting data into a table with an auto-incrementing primary key
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. ID: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}