Search code examples
phpmysqlobjectpdo

pdo, insert php object to database


I can't find an answer to this question.

I want to save a PHP object into a MySQL database. Example:

class user{
  private $id, $email, $pw, $first, $last, $group,.....;
 // getters and setters    
}

class someclass{

public function someFunction(){
  $pdo = new PDO(...);
  $objUser = new user();
  $objUser->setEmail(....);
  $objUser->setFirst(....);
  //bla bla bla

 // and I want to save this user object to the DB with something like:
  $pdo->insert($objUser); //in this case db table equals to class name
  //instead of building/writing query manually. 
  //for mysql_query I have made a class for building queries for insert, update and delete 
  //but mysq_query is old and deprecated
}

}

The main reason I am asking for this is because I don't want to write something that can exists by default.

Thank you.


Solution

  • I would probably implement insert, update and delete methods in the user class, rather than making it a feature of the database class to interpret the object being given to it.

    There is not a built-in method of doing this in PHP or the mysql PDO classes, but some frameworks implement an ORM (object relational mapping) that allow you to specify easily in your object classes how they interact with the database. (Laravel framework ORM docs)

    Here's a very basic way you could implement it.

    class ORM {
        public function insert($pdo) {
            // Get object name
            // Get object properties
            // Check if database table exists with object name
            // Generate and run a query to insert a record into that table
            // using the property names and values
        }
        public function update($pdo) {
            // Like insert, but update
        }
        public function delete($pdo) {
            // Etc...
        }
    }
    
    class user extends ORM {
        private $id, $email, $pw, $first, $last, $group,.....;
        // getters and setters    
    }
    
    class someclass{
        public function someFunction(){
          $pdo = new PDO(...);
          $objUser = new user();
          $objUser->setEmail(....);
          $objUser->setFirst(....);
          //bla bla bla
    
          $objUser->insert($pdo);
        }
    }