Find the last primary key of another table

Put the prepare statement before the loop - you only need to run it once.