$prevProdID instead of $prevProdId fixed it! I must have looked at that line a hundred times and I couldn't see why it wasn't working.

I think that the product_prid may be a little heavier than product_id but it seems OK and feels "right": rarely are there more than a hundred orders in each batch, and it takes very little time to run this script.

Thanks very much for your help.