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:
- Instantiate the object.
- Serialize the object.
- 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:
- Connected to MySQL using the PDO object.
- We instantiated our Person object.
- We used var_dump, just to see what the structure of the object looks like.
- We serialized the object into a string using the PHP function serialize.
- We prepared our INSERT statement.
- 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