Thursday, 9 August 2018

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:
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”:
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:

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:
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.

0 comments:

Post a Comment