I haven't looked too closely, but you seem to be redifining $sth inside the if block. That means that the first time you do
inside the while block, it executes the correct query, but the second time around, $sth refers to your UPDATE query. This will lead to unexpected results. You could rename the $sth inside the if block to something else, or limit its scope with my or local.