Did you try using my code? It fixes that headers already sent, and isn't full of sql injection exploits in literally every possible place one could be
Does the data you are putting into categories contain a ' ? because that would be enough to cause an SQL error in your code.