I don't see anything wrong with you code. So I guess the inputs may bring something wrong. Pay attention to that. Try to print out the final SQL statement to detect where the problem is.