Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store an php object in a MySQL table?

Tags:

object

php

mysql

I have set up a table that has only one field for a BLOB (Binary large object) but when I try to Insert it into the table it throws an error stating that it failed to convert the object to a string. This is my Query:

mysql_query("INSERT INTO objects (inquery) VALUES($inquery)");
like image 757
nkcmr Avatar asked Feb 20 '11 00:02

nkcmr


People also ask

Can you store object in MySQL database?

TEXT data objects, as their namesake implies, are useful for storing long-form text strings in a MySQL database.

Can I store objects in a database?

You can store objects in relational tables as column objects or in object tables as row objects. Those objects that have meaning outside of the relational database they reside in, should be made referenceable as row objects in an object table. Otherwise, they should be stored as column objects in a relational table.

Can we use PHP in MySQL?

With PHP, you can connect to and manipulate databases. MySQL is the most popular database system used with PHP.


2 Answers

Serialize it:

$str = serialize($object);

If your object contains private/protected fields it's also a good idea to base64_encode() the serialized object as those properties will result in ascii-1 characters being used which would break when editing the column manually e.g. with phpMyAdmin..

To restore your object, you simply unserialize() the string (base64_decode() it before if necessary).

like image 154
ThiefMaster Avatar answered Sep 21 '22 05:09

ThiefMaster


use json_encode to encode the object before you save it in Mysql then json_decode to decode the object

like image 41
Mohamed Auf Avatar answered Sep 22 '22 05:09

Mohamed Auf