title: Sorting the results of a mysql query
body: <p>Im having difficulties trying to figure out an elegant solution to sorting the results of a mysql query based on a delimited string.  Ill explain in more detail below</p>
  
  <p>I am creating a database of contacts where individual users can add/remove people from a list.  When the user adds a new contact I append the added contact id to a delimited string and store that data in a database column associated with that user (named contacts):</p>
  
  <pre><code>$userID = ?? //YOUR ID
  $contactID = ?? //WHATEVER THE ADDED USER ID IS
  $confirm = 0 //has the user been confirmed
  $sql = "SELECT contacts FROM user WHERE id = '$userID'";
  $query = mysql_query($sql);
  $row = mysql_fetch_array($query);
  $contact = $row['contacts']; 
  $contact .= '|'.$contactID.':'.$confirm;
  $update = mysql_query("UPDATE user SET contacts = '$contact' WHERE id = '$userID'");
  
  //contact column data might be:  |10:0|18:0|36:0|5:0
  </code></pre>
  
  <p>When the user searches their contacts I grab the data from the contacts column, explode/split the string and return the individual users names:</p>
  
  <pre><code>$userID = ?? //YOUR ID
  $sql = "SELECT contacts FROM user WHERE id = '$userID'";
  $query = mysql_query($sql);
  $row = mysql_fetch_array($query);
  $contacts = explode("|", $row['contacts']);
  foreach($contacts as $item)
  {
   list($contactID,$confirm) = split(":", $item);
   $sql = "SELECT name FROM ".user." WHERE id = '$contactID'";  
   $query = mysql_query($sql);
   $row = mysql_fetch_array($query);
   echo($row['name'].'&lt;BR&gt;');
  }
  </code></pre>
  
  <p>This indeed does return all the names, but it returns them in the order of the delimited string. I cant seem to find an elegant way to sort by name alphabetically.</p>
  
  <p>Should I not store the contacts list in a delimited string? How would you solve this?  </p>