How do I refactor this basic form handler I've dabbled with PHP for a couple of years, I can generally get what I need done and I've been teaching myself PDO. The problem is I want to set it up with classes but i'm not really sure how to. 

Below is my code, which takes data from a form, does some rough checking to see if the email is right and the fields are full. It works but it's gotten to a point where I can't take it further without breaking it or getting confused and i want to add things such as validation. 

So what i'm asking for is can some show me how to create a basic connection class that outputs acouple of records from a database, this would help me a lot if anyone could.

&lt;?php
try{
$host = "localhost";
$dbname = "db";
$user = "user";
$pass = "pass";

  $odb = new PDO("mysql:host=" . $host . ";dbname=" . $dbname, $user, $pass);
  $odb-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  } catch (PDOException $e) {
echo "I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e-&gt;getMessage(), FILE_APPEND);
}

        if($_SERVER["REQUEST_METHOD"] == "POST"){
            if (isset($_POST['firstname']) &amp;&amp; !empty($_POST['lastname']) &amp;&amp; filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) &amp;&amp; !empty($_POST['phone'])){
                $firstname = $_POST['firstname'];
                $lastname = $_POST['lastname'];
                $email = $_POST['email'];
                $phone = $_POST['phone'];

                        $q = "INSERT INTO jobform(firstname, lastname, email, phone) VALUES (:firstname, :lastname, :email, :phone);";
                        $query = $odb-&gt;prepare($q);
                        $results = $query-&gt;execute(array(
                        ":firstname" =&gt; $firstname,
                        ":lastname" =&gt; $lastname,
                        ":email" =&gt; $email,
                        ":phone" =&gt; $phone, 
                        ));
                } else {
            #echo $errMsg;
        }
     }
?&gt;
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.