title: select two random rows in MySQL database
body: <p>I have a database full of images, and I want to spit out and display two random images. This code does it properly, but I'm not convinced that it's the best way to do it, especially if the database will eventually have many many rows.  I've looked into using MySQL's rand() function and limiting it to two results, but from what I've read rand() is relatively slow on large databases.  Another issue is in the double database query.  Is there a better way to select two random rows by img_id?</p>
  
  <p>img_id is an auto_incremented row but cannot be assumed to be continuous.</p>
  
  <pre><code>//get all image ids
  $query = $conn-&gt;prepare('SELECT img_id FROM images');
  $query-&gt;execute();
  $result = $query-&gt;fetchAll();
  
  //create an array in which to put all the ids
  $list_imgs = array();
  
  //put the ids into the array to search over
  for ($x=0; $x &lt; count($result); $x++) {
      array_push($list_imgs, $result[$x]['img_id']);
  }
  
  //output two random images
  for ($x=0; $x &lt; 2; $x++) {
      //create random index for search
      $rand = array_rand($list_imgs);
  
      //query to select one image
      $query = $conn-&gt;prepare('SELECT title, file_loc FROM images WHERE img_id=?');
      //random index value in array of img_ids
      $query-&gt;execute(array($list_imgs[$rand]));
      $result = $query-&gt;fetchAll();
  
      echo 'title:' . $result[0]['file_loc'] . '&lt;br /&gt;&lt;img src="' . $result[0]['file_loc'] . '" /&gt;';
  }
  </code></pre>
  
  <p>any suggestions to make the query more efficient?</p>