MySQL query optimization in codeigniter
05:05 03 Apr 2013

I have function in CodeIgniter to retrieve latest posts from 2 tables:

public function get_latest_comments($amount)
{
  $query = $this->db->query('
    SELECT *, FROM_UNIXTIME(date) AS timestamp
    FROM comments
    ORDER BY timestamp DESC
    LIMIT 5
  ');

  if ($query->num_rows() > 0) {
    $result = $query->result_array();

    for ($i = 0; $i < sizeof( $result ); $i++) {
      $result[$i]['author_info'] = $this->comments_model->get_comment_author( $result[$i]['id'] );
      $result[$i]['date'] = mdate( "%M %m, %Y", $result[$i]['date'] );

      if ($result[$i]['section'] === 'blog') $loc = 'blog_posts';
      if ($result[$i]['section'] === 'core') $loc = 'public_posts';

      $this->db->select( 'title, slug' );
      $query = $this->db->get_where( $loc, array('id' => $result[$i]['location']) );

      $result[$i]['post_title'] = $query->row( 'title' );
      $result[$i]['url'] = base_url() . $result[$i]['section'] . '/view/' . $query->row( 'slug' ) . '/';
    }
    return $result;
  }
  return false;
}

The problem is that it runs too slow. My page sometimes loads 7-8 seconds. I suspect this query running 2 times + similar query gathering latest comments slows down my page.

I have a bad feeling about queries inside the loop. How can I avoid that?

The structure of my table is:

users (id, username, mail ...
user_info ( user_id, name, surname
public_posts ( id, slug, text, author(user id) ...
blog_posts ( id, slug, text ...
comments ( id, text, author, location(post_id_, section(post_table) ...
mysql sql codeigniter