Execution approach

Which of the following approach is best to follow to display the records:

$qry = "select * from data";

$res = mysql_query($qry);

while($row = mysql_fetch_array($res)){
     echo "username: ".$row['username'];
function get_data(){

$qry = "select * from data";

$res = mysql_query($qry);

$data = array();

while($row = mysql_fetch_array($res)){
     $data[]  =  "username: ".$row['username'];

return data;

} //end function get_data()

$mydata = get_data();

foreach($mydata as $name){
echo "username:".$name;

Best approach with respect to execution.

Actually, neither is best because they are both using deprecated mysql functions.

Saying that out of the way. If you are only interested in getting results for the username field, why SELECT * every field? In fact, AFAIK, explicity SELECTing fields is always more efficient than using the “everything wildcard”.

As far as from a design perspective, I think the simpler first example would be good enough for a “one time use” scenario. Where the power of the second example lies is that you can call it multiple times thereby reducing the amount of code writing. But it could be even more useful if you had the function accept arguments eg. specific field names.

Thanks for your quick reply :slight_smile:

I know the difference between wildcard * and relative fields but I just wanna know about the execution from direct fetching and displayed from the already stored array.

I have to display 1000 - 2000 records at once with sorting columns.

pagination and sorting I rendered through javascript but it took much time. I was confusing between how can I make it faster.

I used jquery pagination and sorting feature but still it took time to display the records fast and properly.

Yes, I think it would be faster and more efficient to use a better query (i.e. one that has an ORDER BY in it) than to have either PHP or javascript do the sorting.

You need to limit the query if you are going for pagination. For example:

"select * from data LIMIT 0, 20"

This will get the first 20 records. Then the second page would need a different offset. For example:

"select * from data LIMIT 20, 20"

You could pass into your function a $_GET variable that represents what page your are on. Then you can workout the offset and limt.