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.

4
  • 1
    Possible duplicate of stackoverflow.com/questions/5054485/… Commented Jul 25, 2012 at 17:48
  • You could add a __toString method to your class, then use query("INSERT INTO `table` VALUES (".(string)$user.");");. Commented Jul 25, 2012 at 17:49
  • @arxanas that will get him only half way there. Might as well make a 'saveToDB' method Commented Jul 25, 2012 at 17:53
  • @arxanas that's an interesting approach but I really wouldn't want to maintain an application written like that. Commented Jul 25, 2012 at 17:53

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.