I am writing a chat application for joomla (apache server) and employ this construction to emulate lengthy-polling (server side):

function get_messages($last_id) {
   $time = time();
   while((time() - $time) < 25) {       
      $sql = 'SELECT * FROM #__messages WHERE `id` >'.intval($last_id);
      $db->setQuery($sql);
      $rows = $db->loadAssocList();
      if (count($rows)>0) { 
         echo 'JSON STRING HERE';  
      } else {
     flush();
  } 
   usleep(5000000);       
   }
}

How Do I optimize this a part of code. Must I use infinite looping or must i avoid while construction? P/S: I understand Apache isn't best option to create chat application for and node.js is much better.

Thanks!

Infinite loops will never be advisable simply because they hammer your server assets. You're best getting JS supplying the intermittent polling for your get_messages function. Make use of a timeout and embed the script on any page that shows the messages.

I am likely to answer in line with the limited information I have got that will help you within the largest possible way following industry standards. You have to not code in the manner you presently are since it is very inefficient and to be honest harmful.

This is actually the mootools code needed to operate an intervaled polling (I have used Mootools while you stated you are using Joomla, I have assumed you are using 1.6+ as 1.5 is EOL this month):

//this sets how often you want to update (in milliseconds).
setInterval('chatPoll()',2000);
//this function essentially just grabs the raw data
//from the specified url and dumps it into the specified div
function chatPoll()
{
   var unixTimestamp Math.round(new Date().getTime() / 1000)
   var req = new Request({
      method: 'get',
      url: $('ajax-alert').get('http://www.yoururltoupdate.com/file.php?last=' + (unixTimestamp-2),
      data: { 'do' : '1' },
      onComplete: function(response) { response.inject($('my-chat-wrapper')); }
   }).send();
}

Your PHP file need to look something seem like this:

get_messages($_GET['last']);
function get_messages($last_id) {

      $sql = 'SELECT * FROM #__messages WHERE `id` >'.intval($last_id);
      $db->setQuery($sql);
      $rows = $db->loadAssocList();
      if (count($rows)>0) { 
         echo json_encode($rows);
      }     
}

I've not fully examined this code however it should work and when not will certainly help answer your query regarding how what you are attempting to do ought to be accomplished as opposed to the way you initially published. Should you wanted to obtain fancy you can take a look at node.js too. There's also a lot of extensions for Joomla which act as chat mediums for support reasons if that is that which you were after.