How to save object data in mysql db using php class function?

I created a table in the database with the name "member" from the "name", "college", "email", "zid" fields, now I created a class (in php), for example

class member { private $name,$college,$email,$zid; private function adduser { //function definition } public function autherise($id) { //function definition } } 

now on the index page. I take this value as input from the user using the html form (verified by JS), now on the form's action page. I want to create an object as obj = new member (); then calling the class function as obj-> autherise ($ _ post ['zid']); I want the autherise and adduser functions, like autherise, to check the uniqueness of the zid and adduser calls with the rest of the post variables and save them for the object, and then add the whole object to a single DB query.

I don't want insert into member(name,email,college,zid) values('$name,$email,$college,$zid') I want to enter obj directly in db

You can change anything in the functions.

Thanks in advance!

+4
source share
3 answers

A β€œsimple” solution for storing an entire object somewhere, like in a database, is to serialize it - i.e. converts it to a string; and then save this row in one field in the database.

This can be done in PHP using the serialize function - and to de-serialize strings for an object, use the unserialize function.


Another solution would be to serialize your object in JSON format - it’s great that JSON can be used directly from Javascript and from a variety of different programming languages, using the right libraries.

For JSON see json_encode and json_decode


As a side element: note that if you store your data as serialized strings, it will be much harder to manipulate them in SQL: you cannot update them with a simple SQL query, for example; and the search will be difficult.

This means that you will always have to extract data from the database, manipulate it with PHP and send it back to the database, which may not always be such a good idea, depending on your needs.

+12
source

I'm not sure what you are asking for. But maybe ... maybe you are looking for a relational mapmaker (orm) object , for example, doctrine .

+3
source

If you want to save the object in the database, you can serialize() or json_encode() object in String, and then save it in a field in the table.

When you are ready to use it again, you can unserialize() or json_decode() create the string again.

0
source

Source: https://habr.com/ru/post/1301430/


All Articles