0

My website take too much to load.I want to show a table on top of page and on bottom of page.

To get the same result twice,I am using same query two times.What is the best way to fetch data only once so that we improve speed?

Here is my code AT TOP

$q_s ="SELECT id,ref,name,description FROM TABLE WHERE status=2 AND is_archive=0 
ORDER  BY id DESC limit 5";
     $res = $objApp->query($q_s); 
  while($rw = $objApp->row($res)){
  //display my data here in div1
 }

AT BOTTOM

$q_s2 ="SELECT id,ref,name,description FROM TABLE WHERE status=2 AND is_archive=0 
ORDER  BY id DESC limit 5";
     $res2 = $objApp->query($q_s2); 
  while($rw = $objApp->row($res2)){
  //display my data here in div2
 }

NOTE:DIV1 and DIV2 are two different html.Also i showed only simplest query,its too complecated in my case.

How can i improve it?Sorry i am new to PHP

5
  • Caching doesn't help in all cases. You can always re-use the same result set $res. Commented Oct 21, 2013 at 8:01
  • How i can cache it?and to use $res again,it give me empty... Commented Oct 21, 2013 at 8:02
  • at the very top define an empty array $result = array() and in your first while loop, build it up then use it everywhere you want without the need to query DB Commented Oct 21, 2013 at 8:04
  • @Ahmad:I can not get you?Can you give me an example so that i accept your answer?(if it worked) Commented Oct 21, 2013 at 8:06
  • @Muhammad I have posted an answer with example, hope it helps make it clear for you Commented Oct 21, 2013 at 8:11

1 Answer 1

1

Here is what I would do

$rows = array();

$q_s ="SELECT id,ref,name,description FROM TABLE WHERE status=2 AND is_archive=0 
ORDER  BY id DESC limit 5";
     $res = $objApp->query($q_s); 
  while($row = $objApp->row($res)){
   array_push($row, $rows);
 }

You can use $data in a foreach loop for an example

foreach($rows as $row) {
   echo $row['colname'];
}

Now you can use data anywhere, multiple times in the page without doing any more queries, hope this helps :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.