PHP: Save an object to MySQL database.

This is a tutorial on how to save PHP objects to a MySQL database. This method will also work with other DBMS systems such as SQL Server and PostgreSQL.

Firstly, lets take a look at an example class that I’ve made:

<?php

class Person{
    
    //The name of the person.
    public $name;
    
    //The person's gender.
    protected $gender;
    
    public function __construct($name, $gender) {
        $this->name = $name;
        $this->gender = $gender;
    }
    
    public function speak(){
        echo 'Hi, my name is ' . $this->name . '!';
    }
    
}

As you can see, this Person class is extremely simple and straight-forward. It has two properties: A public property called $name and a protected property called $gender. It also has a constructor, as well as a function called “speak”.

To store this object in our MySQL database, we will need to:

  1. Instantiate the object.
  2. Serialize the object.
  3. Insert it into our MySQL database.

For the purpose of this example, I’ve created a table called “objects”:

//Connect to the MySQL database using the PDO object.
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');

//Instantiate object.
$person = new Person('John Doe', 'Male');

//var_dump the object so that we can see what its structure looks like.
var_dump($person);

//Serialize the object into a string value that we can store in our database.
$serializedObject = serialize($person);

//Prepare our INSERT SQL statement.
$stmt = $pdo->prepare("INSERT INTO objects (data) VALUES (?)");

//Execute the statement and insert our serialized object string.
$stmt->execute(array(
    $serializedObject
));

In the code snippet above, we:

  1. Connected to MySQL using the PDO object.
  2. We instantiated our Person object.
  3. We used var_dump, just to see what the structure of the object looks like.
  4. We serialized the object into a string using the PHP function serialize.
  5. We prepared our INSERT statement.
  6. We executed the statement and inserting our serialized object into our database.

In this case, the serialized string looks like this:

O:6:"Person":2:{s:4:"name";s:8:"John Doe";s:9:"*gender";s:4:"Male";}

Retrieving the object.

Now, we need to retrieve our PHP object from our MySQL database so that we can unserialize it and use it again:

//Connect to the MySQL database using the PDO object.
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');

//Prepare our select statement.
$stmt = $pdo->prepare("SELECT * FROM objects WHERE id = ?");

//Execute the statement.
$stmt->execute(array(1));

//Fetch the table row in question.
$row = $stmt->fetch(PDO::FETCH_ASSOC);

//Unserialize the data.
$person = unserialize($row['data']);

//Lets call the speak method / function on our object.
$person->speak();

In the example above, I retrieved the serialized data from my database. I then unserialized the data back into an object before calling the speak function – just to make sure that everything was working as intended.

Note: More often than not, serializing PHP arrays and objects is a bad idea. Please make sure that this is the best solution to your problem before you embark down this path.

Related: Saving a PHP array to a database.