title: Moodle Reading data from Database: How to SELECT the first record which meets the WHERE clause? TOP does not work
body: <p>I want to retrieve the blog post <em>title of the <strong>latest</strong> blog post by</em> a particular user with the <code>id</code> stored in <code>$myUserId</code>. So <a href="https://docs.moodle.org/dev/Data_manipulation_API" rel="nofollow">from this doc</a>, I have learnt to do this:</p>
  
  <pre><code>$latestPostSubject = $DB-&gt;get_record_sql('SELECT subject FROM {post} WHERE userid = ?', array($meUserId));
  </code></pre>
  
  <p><strong>The problem is that this returns all the blog posts by the user, while I need <em>only the latest one</em>.</strong> </p>
  
  <hr>
  
  <p><strong><em>WHAT I TRIED:</em></strong></p>
  
  <ol>
  <li><p>So when I try something like </p>
  
  <pre><code>$latestPostSubject = $DB-&gt;get_record_sql('SELECT TOP(1) subject FROM {post} WHERE userid = ?', array($meUserId));
  </code></pre>
  
  <p><a href="http://www.techonthenet.com/sql/select_top.php" rel="nofollow">Reference.</a></p>
  
  <p>I get a syntax error.</p></li>
  </ol>
  
  <blockquote>
    <p>Error Reading from Database.</p>
    
    <p>Debug info: You have an error in your SQL syntax; check the manual
    that corresponds to your MySQL server version for the right syntax to
    use near 'FROM mdl_post WHERE userid = '2'' at line 1 SELECT TOP(1) *
    FROM mdl_post WHERE userid = ? [array ( 0 => '2', )] </p>
    
    <p>Error code: dmlreadexception</p>
  </blockquote>
  
  <ol start="2">
  <li><p>The <a href="https://moodle.org/mod/forum/discuss.php?d=195214" rel="nofollow"><code>post</code> table</a> also contains a <code>created</code> and <code>lastmodified</code>
  fields, but when I printed the entire record of the user with the <code>*</code>
  from the <code>post</code> table, I failed to understand the format of the date</p>
  
  <ul>
  <li><p>it's a 10 digit number :s <strong><em>Otherwise I would do some math on the dates on which the blog posts were created.</em></strong></p>
  
  <p>...[lastmodified] => 1432051856 [created] => 1432051855...</p></li>
  </ul></li>
  </ol>
  
  <hr>
  
  <p><strong><em>QUESTION:</em></strong></p>
  
  <p><strong>So what should I do to get the latest blog post from the table?</strong></p>
  
  <p><strong>Secondly, why doesn't the <code>TOP(1)</code> in the SQL statement work?</strong></p>