title: Database design: Matching sql database keys to php constants?
body: <p>Well this is a simple design question I've wondered about many times and never found a satisfying solution for. My example is with php-sql, but this certainly applies to other languages too.  </p>
  
  <p>I have a small database table containing only very few entries, and that almost never needs updating. eg this <code>usertype</code> table:</p>
  
  <pre><code>usertype_id (primary key)  | name       | description
  ---------------------------+------------+-------------------
  1                          | 'admin'    | 'Administrator'
  2                          | 'reguser'  | 'Registered user'
  3                          | 'guest'    | 'Guest'
  </code></pre>
  
  <p>Now in the php code, I often have to check or compare the type of user I'm dealing with. Since the user types are stored in the database, I can either:</p>
  
  <p>1) Select * from the usertype table at class instantiation, and store it in an array.<br>
  Then all the ids are available to the code, and I can do a simple select to get the rows I need. This solution requires an array and a db query every time the class is instantiated.</p>
  
  <pre><code>$query = "SELECT info, foo FROM user WHERE usertype_id = ".$usertypes['admin'];
  </code></pre>
  
  <p>2) Use the <code>name</code> column to select the correct <code>usertype_id</code>, so we can effectively join with other tables. This is more or less equivalent to 1) but without needing to cache the whole usertype table in the php object:</p>
  
  <pre><code>$query = "SELECT info, foo FROM user JOIN usertype USING (usertype_id) WHERE usertype.name = 'admin' ";
  </code></pre>
  
  <p>3) Define constants that match the keys in the usertype table:</p>
  
  <pre><code>// As defines
  define("USERTYPE_ADMIN",1);
  define("USERTYPE_REGUSER",2);
  
  //Or as class constants
  const USERTYPE_ADMIN = 1;
  const USERTYPE_REGUSER = 2;
  </code></pre>
  
  <p>And then do a simple select.</p>
  
  <pre><code>$query = "SELECT info, foo FROM user WHERE usertype_id = " . USERTYPE_ADMIN;
  </code></pre>
  
  <p>This is probably the most resource-efficient solution, but it is bad to maintain, as you have to update both the table and the code if you need to modify something in the usertype table..</p>
  
  <p>4) Scrap the <code>usertype</code> table and only keep the types in the php code. I don't really like this because it lets any value get into the database and get assigned to the type of user. But maybe, all things considered, it isn't so bad and i'm just complicating something that should be simple..</p>
  
  <p>Anyways, to sum it up the solution I like most is #2 because it's coherent and with an index on <code>usertype.name</code>, it can't be that bad. But what I've often ended up using is #3, for efficiency.</p>
  
  <p>How would you do it? Any better solutions? </p>
  
  <p>(edit: fixed query in #2)</p>