PDO Tutorials 1 – Inserting Single Row

A man's got 99 problems, used mysql_query(), now he has 100.When things are urgent, we all go with the spaghetti code. When they are not, well, some of us still do. Here comes the bad news: We shouldn’t.

If it’s about inserting records to database, most of the old tutorials go with the mysql extension functions such as mysql_connect() and/or mysql_query() which actually have been sitting at the center of the security issues, for example the most popular one: SQL injection.

Deprecated: mysql_connect()PHP’s got a lot more clear recently. As of PHP version 5.5.0, using good old mysql extension functions cause a warning that the methods are now deprecated and the one simple should use mysqli functions or PDO instead. It was a recommendation, now it became a must.

In this short tutorial series, I will try to explain how I use PDO in my OOP classes and also will share codes of a small example.

After the 5 tutorials, you’ll be able to:

  1. Insert single row
  2. Do rollback in failure cases
  3. Insert multiple rows
  4. Update multiple rows
  5. Select rows

All with PDO.

1. Inserting Single Row

There are some ways of executing SQL queries with PDO. If you have your SQL statement prepared with params bound to (not recommended), you can use PDO’s exec() function. If you want to use placeholders in your query (PDO uses either ? or :paramName) and then bind parameters (recommended), you can use PDO’s prepare(), bindParam() and execute() methods (in this order). I’ll go with the second.

Since we are going with OOP, it’s a good idea to keep the basic PDO connection code in a class like Connection.

Connection class contains a WOUF (write-once-use-forever) code so there's no need to memorise it. I know I didn't. (Btw, I just made up WOUF)
class Connection
{
    public function dbConnect()
    {
        try {
            $db = new PDO("mysql:host=" . HOST . ";dbname=" . DATABASE. ";charset=utf8", USER, PASS);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        } catch (Exception $e) {
            die("Connection not found. Error Code (".$e->getMessage().")");
        }
        return $db;
    }
}

In our classes, we’ll store a private variable for database connections which is an instance of the Connection class. Line 7 and 8 contains some adjustments for PDO where you can find details here. I’d recommend keeping them like this but you can find discussions on Stack Overflow and make your own decision according to your case.

Now that our connection class is ready, we can write a record function to our custom object.

In this tutorial, I have an object named Object (TY, Captain Obvious) which has two attributes: id and name. They are stored in a database table named... "table". (I like to keep things simple.)
You can find the SQL query to create DB and table and other PHP codes in the repo that I'm going to share at the end of the tutorial.

First of all, we need to create a Connection instance object in our class. Best place to create this instance variable is our class’ __constructor method.

private $db;
public function __construct() {
    // create a new PDO connection instance
    $this->db = new Connection();
    $this->db = $this->db->dbConnect();
}

Now let’s create the recordObject method to use this $db variable to insert our object to database. Row id will be handled by the MySQL server and auto incremented.


// Record function for object with properties set
public function recordObject() {
    // create sql query
    $sql = "INSERT INTO `table` (`name`) VALUES (?) ";
    // prepare connection with the query
    $stmt = $this->db->prepare($sql);
    // bind parameters to query
    $stmt->bindParam(1, $this->name);
    // execute the statement
    if ($stmt->execute()) {
        // if statement has success, set self id to last insert id
        $this->id = $this->db->lastInsertId();
        return true;
    } else {
        return false;
    }
}

As you can see in line 4, our INSERT statement is pretty much the same with an SQL command but it has a placeholder. If I was adding two columns, I’d keep adding placeholders like (?,?). Each one is represented by index (starting from 1).

One of the coolest thing about the PDO is that it handles value types by itself. If we were to use SQL queries directly, we would need to surround our strings with quotation marks. With PDO, all we need to do is just bind the string directly and it will put those marks.

After creating the formatted SQL string, I create a variable to store the PDO statement, I also prepare it with prepare() function to bind parameters in the next step. (line 6)

Now I’m ready to bind parameters to this PDO statement. Since the index of the “name” placeholder is 1, I will bind “name” value to param 1. (line 8)

That’s it. Now we can run this query with PDO’s execute() function which returns BOOLEAN and if it is true, set our object’s id to last insert ID.

Create an index.php file to put it all together and debug.

require_once __dir__."/Object.php";

$object = new Object();
$object->name = "Hello PDO";
if ($object->recordObject()) {
    echo "New record with ID: ".$object->id;
} else {
    echo "Could not record";
}

Run it and you the output should be: “New record with ID: ##”

That’s it for the first tutorial. Now you can insert rows one by one (yet) to database with PDO. You can find the code of this tutorial in the Github repo.

The next tutorial will be about rolling back changes which is ultimately important in such cases that the operation might be broken at some point and some of the records are inserted/updated, the rest are not. PDO can roll back the changes from a given point and it will.

Post a comment