2

I'm working on a website in which I would like to use PHP and MySQL. Mostly I insert hundreds of variables into my MySQL database but I am getting tired of this. I have searched the internet for a solution but without any succes.

My website uses Object Oriented PHP and I would like to insert the whole instance into the database. Example:

class User
{
     private $userID;
     private $username;
     // etc

     public function __construct($userID, $username)
     {
           $this->userID = $userID;
           $this->username = $username
     }

     // Other functions go here
}

I would like to know if I could save a whole instance ($user = new User($x, $y)) into my MySQL database. If possible, what field type do I need?

Thanks in advance.

Rick Slinkman
  • 643
  • 10
  • 23

3 Answers3

2

What you're looking for is probably an ORM (object relational mapper), which allows you to map directly your objects to tables in the database.

Several PHP ORMs are available, for instance :

  • Doctrine, perhaps the most widely used one,
  • Propel
  • Redbean which has a bit of a different approach, but I like that one quite a lot.

You should also be aware of the fact that using such a library might impact performance quite a bit, but with caching and other solutions this can be mitigated.

Manu Clementz
  • 1,807
  • 12
  • 19
  • Thanks for the tip. Where we work we use Doctrine. I thought about implementing Doctrine for my website, but my website is only small and a more simple way will do :) Thanks for the tip anyway! – Rick Slinkman Jul 25 '12 at 18:15
2

You should serialize the object somehow and store it in a text field. You can use either PHP's native serialize()/unserialize() or, if they are simple value-objects, you could use json_encode()/json_decode(). See this thread for more information/compare of the two

Community
  • 1
  • 1
solidau
  • 4,021
  • 3
  • 24
  • 45
  • Thanks for this. I had already found serialize() and unserialize() but they didn't seem sufficient for the job. I experimented a little and it worked. Thanks! – Rick Slinkman Jul 25 '12 at 18:13
-1

You can't save an instance into database. Because instance is occupied memory where using the compiler it saves states of the class. However Manu Letroll has given a good solution you should use orm to make work easier.

ARIF MAHMUD RANA
  • 5,026
  • 3
  • 31
  • 58