Re: Databases, arrays and woes

From: Date: Thu, 30 Aug 2001 13:49:01 +0000
Subject: Re: Databases, arrays and woes
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-65280@lists.php.net to get a copy of this message
"Kath" <kath@kathweb.net> wrote in message news:015301c13156$2c273500$82e53181@resnet.sunysb.edu... > I have a MySQL table which stores information like this: > > | Type | Place Name | Place Abbrv | > > and lets say I have data in the table like: > > Example #1: > | Office | Bill's Office | bo | > | Store | Millcreek Supply | mcs | > | Office | Harry's Office | ho | > | Store | Sam's Discount Taxidermy | sdt | > | Shipping | East Coast Distribution Facility | ecdf | > > What I'd like to do is be able to have PHP grab the information out of the > database and sort like this on a webpage: > > Type Name #1: > - Place Name (with hyperlink using the abbrv) > - Place Name (with hyperlink using the abbrv) > > Type Name #2: > - Place Name (with hyperlink using the abbrv) > - Place Name (with hyperlink using the abbrv) > > What is the best way to do this? I've tried arrays, different MySQL calls, > voodoo, ouija boards and drinking, but nothing has gotten me what I need. This is a recurrent question; I'm going to write a quick answers page for the _next_ 20 people who ask this. Basically, the answer is a mix of MySQL and PHP: In MySQL, query your records, sorted by the header column (so that all occurrences with the same value are together). In PHP, keep a 'last-known header' variable. If the next header doesn't match the previous one, you're starting a new block - so print a new header. Otherwise, you're continuing an existing block, so skip the header. <?php $conn = @mysql_pconnect("host", "user", "pwd") or die("Error connecting: ".mysql_error()); $query = "SELECT type, placename, placeabbrv " ."FROM places " ."ORDER BY type,placename"; $res = @mysql_db_query("db", $query, $conn) or die("Error querying: ".mysql_error()); $lasttype = ""; echo "\n\t<ul>"; while ($row = mysql_fetch_array($res)) { extract($row); if ($lasttype != $type) { echo "\n\t</ul>\n<br>$type\n\t<ul>"; $lasttype = $type; } echo "\n\t\t<li><a href='places_$placeabbrv.html'>$placename</a></li>"; } echo "\n\t</ul>"; ?> Hope that helps.

« previous php.general (#65280) next »