After discovering the problem, however, I feel like banging my head onto the desk until i'm unconsions. If anyone is interested, here's what was going on.
Inside the first if statement (the one to check for digits in the query) there was a SQL statement, which was inside an $SQL=<<"EOT"; statement. Now, the thing was, the EOT was indented. So it treated the EOT as part of the text, not an isntruction to end it. The only reason I didn't get errors pointing me to it was because there was another EOT connected to another SQL query which was inside another if statement further down in the file. So about 3 quarters of my code was being passed to mysql rather than being evaluated. I feel so stupid.
The only awy I found out was because I DID get an error when I started to randomly comment out large sections of the code.
Man I feel so stupid. How could I not have seen this earlier, this problem has been there since I started work on this script.
Again, thanks for that solution.