Sort ORDER BY links for each COLUMN of MYSQL database in PHP page?

  • Thread starter Thread starter Jazzidyjazz
  • Start date Start date
J

Jazzidyjazz

Guest
These are the links I am currently using but they are just on the bottom of the page int he middle of no where...

<p>Sort By:</p>
<p><a href="address.php">address</a></p>
<p><a href="email.php">email</a></p>
<p><a href="name.php">name</a></p>
<p><a href="phone.php">phone</a></p>
<p><a href="tvprogram.php">tvprogram</a></p>
I currently have a form where users input their data (form.php). This information goes into MYSQL database (form_data). The information is then recalled by (userdata.php) for our advertisers to see. If they would like to sort by TVProgram or Name it has to be a new page, I believe. But how can I add that link to the new page with the new "ORDER BY" query. I have created some links on top that link to four different php pages, but how can I make those links be on the column header title things...PLease help!
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM form_data ORDER BY address ASC")
or die(mysql_error());

echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Phone</th> <th>Address</th> <th>Email</th> <th>TV Program</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo $row['phone'];
echo "</td><td>";
echo $row['address'];
echo "</td><td>";
echo $row['email'];
echo "</td><td>";
echo $row['tvprogram'];
echo "</td></tr>";
}

echo "</table>";
 
This is an HTML issue. You would add the links the same way you'd add any link, with a anchor tag and the href value pointing to the PHP script.

Instead of using different pages for each sort, try this. Write one script that retrieves the data. Create multiple query strings with different sort orders.

Now you need to add the link to that page to the column headings (as I described above), but add a URL query string that indicates which sort you want. You'll have to parse that string when the script is called, but you can use one script instead of four.

So, you could have a URL called this:

".../datascript.php"

that does a basic search and display. Now, if someone want to sort the TV Show column, you use the same script, but send it like this:

".../datascript.php?tvshow"

At the beginning of the script, have it check for the presence of a query string. If non, run as normal. If there's one, place it in a variable and run the SQL query that relates to that variable or value. Then display the same page with the requested sort order.

It's a bit complicated to explain here, but this should get you started.
 
Back
Top