Page 1 of 1

Stop repeating queries?

Posted: Wed Oct 21, 2009 6:16 am
by sheepysheep
Hiya, just wondering - at the moment I have code such as:

Code: Select all

 
<?php 
$query = "SELECT * FROM accounts WHERE account_id={$account_ref}";
    $results = mysql_query($query);
    while($line = mysql_fetch_array($results)) {
        echo $line['name'];
        echo "<br/>";
    }
 
    $query = "SELECT * FROM accounts WHERE account_id={$account_ref}";
    $results = mysql_query($query);
    while($line = mysql_fetch_array($results)) {
        echo $line['max_users'];
        echo "<br/>";
    }
                
    $query = "SELECT * FROM accounts WHERE account_id={$account_ref}";
    $results = mysql_query($query);
    while($line = mysql_fetch_array($results)) {
        echo $line['account_id'];
        echo "<br/>";
    }
?>
 
Which just seems like a complete waste of time, repeating the code first of all, but also the fact that I am performing 3 queries, when in theory the first time I could just retrieve all the information, then print it out.

Should I be retrieving my data in a different way first - i.e. filling a group of array and then using the array data rather than multiple queries, or is this still the best way of going about it?

Many thanks in advance, hope you're all having a cool day!

Re: Stop repeating queries?

Posted: Wed Oct 21, 2009 6:26 am
by Mark Baker
Database access is probably your single biggest performance overhead, so generally you should be making as few queries as practical. In this case, where all three queries are identical, it would be far better to make a single query, loop through the resultset building an array, then loop through the array for your echoes.

Re: Stop repeating queries?

Posted: Wed Oct 21, 2009 8:20 am
by sheepysheep
Thank you for the input.