Hello all,

Total newbie here..to the site and web dev in general, so go easy on me! lol

Anyways, I have developed a 2 page logging site that allows you to 1.enter data into a db and 2.view the data in the DB in a table.

I'm not sure how its currently being sorted, but when you view the data it appears to be in some random order.

I would like to have the data sorted by date, and eventually have it sort-able by clicking links in the table headers.
Here is some of the code from the page, let me know if you need more.
THanks in advance for any help pointing me in the right direction!

P.S. a co worker helped me right this, I have only a mild understanding of wtf is actually going on here, but I believe its enough to figure this out. thanks!

<?php

echo "<table border=1 cellspacing=3>";
echo "<tr><th>First</th><th>Last</th><th>Date</th><th>Servers</th><th>Notes</th></tr>";

$result1 = mysql_query("SELECT FROM logs");
while ( $row1 = mysql_fetch_array($result1) ) {
echo "<tr>";
echo("<td>" . $row1["First"] . "</td>");
echo("<td>" . $row1["Last"] . "</td>");
echo("<td>" . $row1["Date"] . "</td>");
echo("<td>");
$result2 = mysql_query("SELECT
FROM servers where log_id=".$row1['id']);
while ( $row2 = mysql_fetch_array($result2) ) {
echo( $row2["server_name"] . ",");
}
echo( "</td>");
echo("<td>" . $row1["Notes"] . "</td>");
echo "</tr>";

}
echo "</table>";

?>

    Sounds like you want to add an ORDER BY clause to your DB query?

      thanks dog, that was easy and works well.

        If you wish to implement easy but simple reordering functionality, turn your table headers into links with

        printf('<a href="?orderby=%s">%s</a>',
        	urlencode($orderby),
        	htmlspecialchars($orderby, ENT_QUOTES, 'utf-8')
        );
        

        And then in the script for that page, add

        $ok_orderby = array('Date', 'First', 'Last');
        # First line: check if orderby is set,
        # Second line: check that it doesn't contain any crap it shouldn't
        if (!isset($_GET['orderby']) ||
        	!in_array($_GET['orderby'])
        {
        	# Default sorting
        	$orderby = 'Date';
        }
        else
        {
        	$orderby = $_GET['orderby'];
        }
        
        # Always specify the columns you select, never use *
        $query = sprintf('SELECT First, Last, Date FROM logs ORDER BY %s',
        	$orderby
        );
        
        # Don't use mysql_query. It's been deprecated a long time ago.
        # Switch to the mysqli_* functions, or use PDO instead.
        mysql_query(...)
        

        If you want the table to be sortable without sending a new page request, you'd have to find a javascript library which handles HTML tables to make them sortable, such as tablesorter 2.0 for jQuery. Well, either that or code it yourself.

          Write a Reply...