Sorting Data


How about sorting your data? Couldn't be easier. Just connect to the database as usual:

 $connection = mysql_connect("localhost","root","")     or die ("Couldn't connect to server"); $db = mysql_select_db("produce",$connection)     or die ("Couldn't select database"); 

Then when you read your data, use the ORDER BY clause to indicate what field you want to sort on. For example, if you want to sort by name of the various fruits, use this statement:

 $query = "SELECT * FROM fruit ORDER BY name";         .         .         . 

And then execute this new SQL statement:

 $query = "SELECT * FROM fruit ORDER BY name"; $result = mysql_query($query)     or die("Query failed: ".mysql_error()); 

You can see how this works in phpdatasort.php, Example 8-7.

Example 8-7. Sorting data, phpdatasort.php
 <HTML>     <HEAD>         <TITLE>             Sorting data         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Sorting data             </H1>             <?php                  $connection = mysql_connect("localhost","root","")                      or die ("Couldn't connect to server");                  $db = mysql_select_db("produce",$connection)                      or die ("Couldn't select database");                  $query = "SELECT * FROM fruit ORDER BY name";                  $result = mysql_query($query)                       or die("Query failed: ".mysql_error());                  echo "<TABLE BORDER='1'>";                  echo "<TR>";                  echo "<TH>Name</TH><TH>Number</TH>";                  echo "</TR>";                  while ($row = mysql_fetch_array($result))                  {                      echo "<TR>";                      echo "<TD>", $row['name'], "</TD><TD>",                                   $row['number'], "</TD>";                      echo "</TR>";                  }                  echo "</TABLE>";                  mysql_close($connection);              ?>          </CENTER>     </BODY> </HTML> 

The results appear in Figure 8-7, where the fruit table's data has been sorted by name. Sorting rows is useful when you're preparing your data to display to users.

Figure 8-7. Sorting data.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net