After reading the discussion here (How to reset AUTO_INCREMENT in MySQL?) and ViralPatel's post (https://www.viralpatel.net/reseting-mysql-autoincrement-column/) and a few more posts, I found out that the problem with ALTER TABLE tablename AUTO_INCREMENT = 1
is that it still won't "restart" an id (which is an INT primary key). I also tried it myself but the id just kept incrementing from the last existing id in the table. I want to avoid having to explicitly declare an id for my database. Particularly, this quote:
Note that you cannot reset the counter to a value less than or equal to any that have already been used. For MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum plus one. For InnoDB, if the value is less than the current maximum value in the column, no error occurs and the current sequence value is not changed.
I came up with this function but I am worried that it will be a bad thing because it HAS to retrieve the whole column of ids before returning a new id.
function id_from_one($table, $id_column_name) {
include 'includes/dbh.inc.php'; // This just creates the $conn variable and connects to the database.
$counter = 1;
$sql = "SELECT $id_column FROM $table;";
$result = $conn->query($sql);
if ($result) {
while ($row = $result->fetch_assoc()) {
if ($counter == $row[$id_column_name]) { $counter++; }
else { break; }
}
}
$conn->close();
return $counter;
}
Am I understanding this correctly? Or is there actually a way to do this? Why does MySQL do that anyway?