PHP Snippet 3:
/* Assume that you want to insert into a table called the_table with columns id, col1, col2, col3 a new row with values for the three cols
$value1, $value2, $value3 respectively, using an existing 'gap' in the id numbering: */
/* Get an array of all present ids: */
$arr = [];
$q1 = mysqli_query($con,"SELECT id from the_table");
while(list($id) = mysqli_fetch_array($q1)){
$arr[] = $id;
}
/* Get the currently largest id in the table as $largest_id */
$q2 = mysqli_query($con,"SELECT MAX(id) from the_table");
list($largest_id) = mysqli_fetch_array($q2);
/* Loop through all integers up to $largest_id + 1 */
/* And do the insert operation just one time, once you find a number not in $arr */
/* Use the $not_yet_inserted variable to break out of the loop */
$not_yet_inserted = true;
for($j = 1; $j <= $largest_id + 1; $j += 1){
if(!in_array($j,$arr) && $not_yet_inserted ){
mysqli_query($con,"INSERT INTO the_table (id, col1, col2,col3) values ('$j','$value1','$value3,'$value3'')");
$not_yet_inserted = false;
}
}