added more error checking, and also add a debug parameter to output the MySQL statement on debug=true