Simple cycle that pick next free id What I'm trying to do is function working like this:

function my_function($id){
   while($id){
      if($id = not free){
          $id=$id+'1';
      } else {
          return $id;
      }
   }
}


I'm new to php and drupal generally and can't figure out how to handle this cycle.
For instance, 'if statement' should test if the id is already in database. If it is then +1 to id if not return this free id.

I'm using this to check whether the id is free or not:

$check_unique_station_id = 'SELECT field_station_id_value FROM {field_data_field_station_id} WHERE field_station_id_value = :input_id LIMIT 1';   
if (db_query($check_unique_station_id, array(':input_id'=&gt;$input_id))-&gt;fetchField()){

}


Any help would be appreciated.

//EDIT

I guess I didn't explain it well. I have custom module and few custom fields. One of them is 'station_id' which is field for storing number (type) of station. Let's say it is a name of the station expressed in number.
Here is an example of values I have in database in field_station_id:


22
45
89


Now what I want to do: when user input=22 then check if 22 already exists and if so check if exist 22+1. When input=45 then return 46 etc.
Now I see that I explained it really bad. Hope that now you know what I mean.

// EDIT 2
// MY SOLUTION

I came up with this piece of code. However I was just wondering if there is some query function to do it (propably faster). As mentioned by Felix downthere (pick as the right answer) it seems that the only query function founds the maximum number in db and return it. Which is not what I want.

Here is my code:

function free_value($occupied_value){

// loads all used values from db
$query_all_occupied_values = 'SELECT field_station_value FROM {field_data_field_station_value} WHERE field_station_value &gt;= :occupied_value ORDER BY field_station_value';
$all_occupied_values = db_query($query_all_occupied_values, array(':occupied_value'=&gt;$occupied_value))-&gt;fetchAll();

// count number of rows of used station_values
$number_of_values = count($all_occupied_values)-1;

// finds first closest value which is not occupied in db
for($i=0; $i&lt;=$number_of_values; $i++) {
    if($occupied_value == $all_occupied_values[$i]-&gt;field_station_value) {
        $occupied_value = $occupied_value+1;
    } else {
        break;
    }
}

$free_value = $occupied_value;

return $free_value;


}
This will select the next free ID:

$next_free_id = db_query("SELECT MAX(field_name) + 1 FROM table_name")-&gt;fetchField();