'MySQL query id generation

I have table and when I add a new row I want to calculat an id number to it.

conditions:

if i have missing number give the smallest one (3) if i have no missing number than give the next number that comes in a row (5)

How can I build this conditions into my query?

My query:

INSERT INTO sample(product) VALUES ('$product')

table

product id
name1 1
name2 2
name4 4

solution if I have missing id

product id
name1 1
name2 2
name4 4
name5 3

solution if I have no missing id

product id
name1 1
name2 2
name3 3
name4 4
name5 5


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source