ok, I sort of understand what it is doing.
but it looks like you just need to do some basic debugging.
this is what I nomally do in situations like this.
1) start at the top of the script as specified in your form's action attribute and add
echo 'got here'; die();
2) run your form to check if it gets to your php script
3) then move the above echo/die down, line by line if you have to, and add appropriate echo statements to display values of variables and then run the form again each time you move the echos.
4) as part of 3) insert the echos in each part of conditional blocks (IF blocks) to check your code logic is correct
keep doing this until your echos show something is not right. then back track your code to fix the error.
5) keep repeating 3) and 4) until you get to the end of your script and it works ok.
if you have a debugger, then debugguing will be easier as you can set break points and check values of variables which is essentially what the above steps are doing.