macoln Posted January 21, 2010 Share Posted January 21, 2010 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? Quote Link to comment https://forums.phpfreaks.com/topic/189290-why-do-i-have-to-query-more-than-once/ Share on other sites More sharing options...
ignace Posted January 21, 2010 Share Posted January 21, 2010 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 Quote Link to comment https://forums.phpfreaks.com/topic/189290-why-do-i-have-to-query-more-than-once/#findComment-999315 Share on other sites More sharing options...
roopurt18 Posted January 21, 2010 Share Posted January 21, 2010 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 Quote Link to comment https://forums.phpfreaks.com/topic/189290-why-do-i-have-to-query-more-than-once/#findComment-999394 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.