title: Work with database in classes
body: <p>I´m wondering how to work with database in classes. For example how to write queries for easy future edit and by OOP rules.</p>
  
  <p>First example:</p>
  
  <pre><code>    class User {
  
      public function select($query) {
          //work with data
          return $data;
      }
  
      public function insert($query) {
          //work with data
      }
  }
  </code></pre>
  
  <p>In this example user (me) add queries for each method. For me, big disadvantage is that I must remember correct form of my query. This example is easy to understand, but in case I will work with more complex queries, it would hard to write correct form of query.</p>
  
  <p>Next example:</p>
  
  <pre><code>class User {
  
      const select = "SELECT * FROM user WHERE ID = ?";
      const insert = "INSERT INTO user VALUES (?)";
  
      public function select($id) {
          //work with data
          return $data;
      }
  
      public function insert($id) {
          //work with data
      }
  }
  </code></pre>
  
  <p>I defined each query as contstant. This form of class is very handy but on the other hand if I want to get ID of user I can't, because I would know name of ID field in the database. This problem I solve in third example</p>
  
  <p>Third example:</p>
  
  <pre><code>class User {
  
      private $table, $idField;
  
      public function setDatabaseInformation($table, $idField) {
          $this-&gt;table = $table;
          $this-&gt;idField = $idField;
      }
  
      public function select($id) {
          //work with data
          //query as SELECT * FROM $this-&gt;table WHERE $this-&gt;idField = ?
          return $data;
      }
  
      public function insert($id) {
          //query as INSERT INTO $this-&gt;table VALUES (?)";
          //work with data
      }
  
  }
  </code></pre>
  
  <p>Personaly I think, this example is the best, because there I have everything what I want and I can't rememeber forms of queries. On the other hand, this example is a bit longer, very universal and I don't know it is correct by OOP rules.</p>
  
  <p>My questions are: Is there any other options how to write queries in database? Is the last example correct by OOP rules? Which way do you use?</p>
  
  <p>Thanks for suggestions.</p>