You could try this library: http://code.google.com/p/php-sql-parser/.
I’ve not used it yet so I can’t guarantee it but the code looks like
it will be able to tell the difference between valid and invalid SQL.Another option could be to use transactions if your SQL variant allows
it. A transaction would allow you to execute the SQL and then cancel
it afterwards reversing any damage that was done. I think I would
prefer option 1 though.
I am quoting Godwin. Source
1
solved Check if SQL input is valid SQL [duplicate]