Stop repeating queries?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sheepysheep
Forum Newbie
Posts: 9
Joined: Mon Oct 12, 2009 8:14 am

Stop repeating queries?

Post 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!
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Stop repeating queries?

Post 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.
sheepysheep
Forum Newbie
Posts: 9
Joined: Mon Oct 12, 2009 8:14 am

Re: Stop repeating queries?

Post by sheepysheep »

Thank you for the input.
Post Reply