Reputation: 663
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.
Upvotes: 2
Views: 1225
Reputation: 5166
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.
Upvotes: -1
Reputation: 4081
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
Upvotes: 2
Reputation: 1797
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 :
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.
Upvotes: 2