I feel it is a logical error .
You are doing a redirect inside a while loop;
I feel instead of this declare a boolean variable assign its value=true even before you iterate over the list.
Then inside the if condition block (when the result of if condition is true) make the value of boolean variable as "false" and break the while loop immediately from if block.
Then immediately outside the while block check for the value of boolean variable , if its value is false then call the redirect. If the value of boolean variable is true only then do the insert operation.