I have a table with id
column. id
s are in ascending order but not necessarily consecutive. For example: 1, 2, 3, 5, 6, 10, 11, 12
I need to find the next "free" id, i.e. max(id) + 1 (or 1 if the table is empty).
Currently I'm doing this in PHP like this:
function get_free_id($con) {
$sql = "SELECT MAX(id) AS last_id FROM Table";
$last_id_query = mysql_query($sql, $con);
$last_id_result = mysql_fetch_array($last_id_query);
$last_id = $last_id_result['last_id'];
return ($last_id == NULL) ? 1 : ($last_id + 1);
}
I have a feeling that this function is "too long" for this simple task and that this can be done much simpler.
Am I right ? How ?