prepare statement not getting deallocated
User-defined variables such as @whereclause and @query will retain their values between calls. I.e. the variables get a value from call #1 to the procedure and will then keep those values when you get to call #2. That is why you have to initialise the variables to make your procedure work.

However, instead of using user-defined variables, it is good practice to DECLARE variables inside the procedure:

DECLARE whereclause TEXT unsigned DEFAULT NULL;
DECLARE query TEXT unsigned DEFAULT NULL; 


(For these kinds of variables you don't prefix them with the '@' character.)