Jump to content

Recommended Posts

Hi, first time posting! I have a MYSQL table of company information, and I want to output it to HTML, categorized with headings like "Association" and "Consultant". So I query my table putting * in $result, then say,

 

[pre]while($row = mysql_fetch_array($result)) {

    if ($row['Type'] == "Association") {

        eval ($printdata);

    }

}[/pre]and then again for Type == "Contractor"

 

Now when I test it, all the Associations output fine, but Contractors are blank. In order to get both, I have to query my table again. But why is that necessary? What happens to $result?

Link to comment
https://forums.phpfreaks.com/topic/189290-why-do-i-have-to-query-more-than-once/
Share on other sites

First off:

 

ORDER BY Type

 

In your query. Then using PHP:

 

$type = '';
while ($row = mysql_fetch_assoc($result)) {
    if ($type !== $row['Type']) {
        $type = $row['Type'];
        print "<h2>$type</h2>";
    }
    echo '<p>', $row['CompanyName'], '</p>';
}

 

This will give you something like:

 

Association
CompanyName1
CompanyName2
CompanyName3

Consultant
CompanyName4
CompanyName5
CompanyName6

Contractor
CompanyName7
CompanyName8
CompanyName9

ignace has the right idea; with his solution you'll only need to loop over the result-set once.

 

In any case, $result is a resource that represents the results of the query.  The resource contains an internal record pointer.  If you want to be inefficient and loop over your results multiple times, you can set the internal record pointer's position:

http://www.php.net/manual/en/function.mysql-data-seek.php

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.