How do I refactor this basic form handler
I know you're asking for "a basic connection class", but you really need a few classes. Currently, your code has all of these (tightly-coupled) responsibilities:


Database access
Error reporting
Form validation
Data persistence
And I assume you're rendering output as well


To move past the difficulties you're facing, you need to separate these concerns into loosely-coupled objects. The prevailing architectural pattern to accomplish this is with the MVC pattern, but this is out of the scope of your question.

With this in mind, I would start with trying to isolate database access. To decouple your data from the rest, you need to put all of your database access in a separate class or set of classes. Here, there are two key patterns: object-relational mapping (ORM) and the database repository. 

With ORM, you essentially try to hydrate database records into PHP objects – if you want to create a new record in the database, you create a PHP object and call a method to persist it to the database; if you want to update a record, you fetch a record, convert it to a PHP object (hydration), update the PHP object, then persist it; to delete, you either obtain a reference to a record or create a dummy PHP object, call a method to delete this record, then call another method to persist this change.

ORM has a lot of surface area; it typically relies on a database abstraction layer, requires you to write a new class for every type of record you'd like to persist, and can confuse beginners when you throw relations into the mix. While this definitely takes some investment, it provides a path to a lot of other benefits: code reuse, testing, automatic schema generation, migrations, validation, etc.

Another pattern for data persistence is the database repository. Here, all you're doing is wrapping your queries in methods and grouping these methods into classes based on which records the queries operate on. For instance, a UserRepository class might have the following methods: UserRepository::createUser(), UserRepository::getUserById(), UserRepository::getUsersByZipcode(), UserRepository::updateUser(), UserRepository::deleteUser(). Each one of these methods would accept a set of PHP parameters (arrays or ORM object and integers), perform database queries based on this data, and return the results (possibly hydrating them).

ORM and database repositories work very well together. I've personally used Doctrine 2's ORM and DBAL as well as Aura SQL's DBAL and would recommend both. I personally would start with creating a connection object with Aura SQL, then create your own class called UserRepository with the methods I listed above. Instantiate the UserRepository class by passing the AuraSQL connection object to it's constructor, then call UserRepository::createUser() to persist the user data from your form. After this, I would consider how to improve your form validation and look into using a template system like Twig.