in reply to processing logic help

I will just comment on the ID's. Keep a number that you can index with:
$next_id = ($id + 1) % 10000;
and then produce the ID you search for with
$named_id = sprintf('%04d', $id);
I will let you fill in the rest of the code around this idea.