• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

Sorting Results

AMDbuilder

Limp Gawd
Joined
Nov 16, 2006
Messages
203
Hello,

I am trying to pull a list out of a DB and permit users to change the sort order of each column, but I can't seam to find anything on how to create the link that when clicked will change the sort order of that column.

Can anyone point me in the right direction as to how I would modify this code so the header name when clicked will change the sort order from an ID column to ASC for that column and then when click again it changes to DESC?

Thanks
AMDbuilder

I'm also open to programs to create the code to do things with DBs and I create a nice front end that would be another welcome alternative until I finally learn php.

Code:
		  <table>
            <?php
				$con = mysql_connect("localhost","user","pass");
					if (!$con)
					{
					die('Could not connect: ' . mysql_error());
					}
					mysql_select_db("table", $con);

					$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY ID");

					echo '<tr>' . "\n";
						echo '<th class="top" scope="col">Club Name</th>' . "\n"; 
						echo '<th class="top" scope="col">Location</th>' . "\n";
						echo '<th class="top" scope="col">More Info</th>' . "\n";
					echo '</tr>' . "\n";

					while($row = mysql_fetch_array($result))
                       {
					echo '<tr>' . "\n";
							echo '<td>' . $row['Club Name'] . '</td>' . "\n";
							echo '<td>' . " " . $row['Location'] . '</td>' . "\n";
							echo '<td>' . " " . $row['More Info'] . '</td>' . "\n";
					echo '</tr>' . "\n";
						}

					mysql_close($con);
			?>
          </table>
 
Code:
		  <table>
            <?php

$order = $_GET['order'];
if (isset($order)) {
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY $order ");
}
else {
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY ID");
}
				$con = mysql_connect("localhost","user","pass");
					if (!$con)
					{
					die('Could not connect: ' . mysql_error());
					}
					mysql_select_db("table", $con);

					$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY ID");

					echo '<tr>' . "\n";
						echo '<th class="top" scope="col">Club Name</th>' . "\n"; 
						echo '<th class="top" scope="col">Location</th>' . "\n";
						echo '<th class="top" scope="col">More Info</th>' . "\n";
					echo '</tr>' . "\n";

					while($row = mysql_fetch_array($result))
                       {
					echo '<tr>' . "\n";
							echo '<td>' . $row['Club Name'] . '</td>' . "\n";
							echo '<td>' . " " . $row['Location'] . '</td>' . "\n";
							echo '<td>' . " " . $row['More Info'] . '</td>' . "\n";
					echo '</tr>' . "\n";
						}

					mysql_close($con);
			?>
          </table>

Something like that would probably work, you would have to make the column names links that would go with the name ex(Column Location would have a link like
Code:
<a href="?order=location">Location</a>
You would also have to protect the query from mysql injection by protecting the $order variable.

-Hope this was helpfull
TopGun
 
Depending on how much data is being returned from the query, there may not be a reason to query the database again just to resort the data. He is a javascript example.
 
Dang you guys are quick!

Thanks for the information! I love the JavaScript one it looks and works great, but this project isn't very big say 100 rows or less. I think for now the method TopGun provided is just the ticket.

One question tho TopGun, how would I got about protecting for mysql injections? I normally don't go beyond predone scripts or php include so I don't want to create any risks due to stupidity.

Thanks
AMDbuilder
 
Actually for that the best way to protect it would be:
Code:
		  <table>
            <?php
$order = $_GET['order'];

if ($order = "") {
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY id");
}

switch($order) {
case "location":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Location");

case "name":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Club Name");

case "info":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY More Info");
}


				$con = mysql_connect("localhost","user","pass");
					if (!$con)
					{
					die('Could not connect: ' . mysql_error());
					}
					mysql_select_db("table", $con);

					echo '<tr>' . "\n";
						echo '<th class="top" scope="col"><a href=\"?order=name\"Club Name</th>' . "\n"; 
						echo '<th class="top" scope="col"><a href=\"?order=location\">Location</a></th>' . "\n";
						echo '<th class="top" scope="col"><a href=\"?order=info\">More Info</a></th>' . "\n";
					echo '</tr>' . "\n";

					while($row = mysql_fetch_array($result))
                       {
					echo '<tr>' . "\n";
							echo '<td>' . $row['Club Name'] . '</td>' . "\n";
							echo '<td>' . " " . $row['Location'] . '</td>' . "\n";
							echo '<td>' . " " . $row['More Info'] . '</td>' . "\n";
					echo '</tr>' . "\n";
						}

					mysql_close($con);
			?>
          </table>

You'll have to try it out to make sure it works, but that is probably the safest way to
do that, because it only accepts the order methods you set.
 
Hello,

Thanks for the information, but when I just tried the code it just gives me errors...

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\xampp\htdocs\beta\testing.php on line 90

Line 90:
Code:
while($row = mysql_fetch_array($result))

My limited php skills are saying there shouldn't be an error, but that's not the case. I wouldn't mind solving this one on my own (gotta learn php some day), but could someone point me in the right direction on where I should be looking?

Thanks
AMDbuilder
 
Hello,

Thanks for the information, but when I just tried the code it just gives me errors...

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\xampp\htdocs\beta\testing.php on line 90

Line 90:
Code:
while($row = mysql_fetch_array($result))

My limited php skills are saying there shouldn't be an error, but that's not the case. I wouldn't mind solving this one on my own (gotta learn php some day), but could someone point me in the right direction on where I should be looking?

Thanks
AMDbuilder

Usually that means there is an error in the query so whatever the query returned did not make $result into a valid MySQL resource. Try adding "or die(mysql_error())" to the end of the query line so you can see any error message that the query might throw.

So it would look something like this:
Code:
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Location") or die(mysql_error());
 
I've done some things very similar, and like the last example TopGun posted, I've used a switch statement, to check and set values, based on what they clicked to sort. In the switch statement you can also add a default at the end, so even if order equals something other then say the "location," "name," and "info" it'll order by "id" by default.

Another thing to consider, if you do it the way posted with a switch statement, is the possibility of maybe changing the query down the road. The way posted would mean you'd have to edit multiple lines of code, since the query is in each case, in the switch statement. If there are only a few cases it might not be a big deal, but you could do it this way:

Code:
<?php

switch($order) {
   case "location":
      $sort_by = "Location";
      break;
   case "name":
      $sort_by = "Club_Name";
      break;
   case "info":
      $sort_by = "More_Info";
      break;
   default:
      $sort_by = "id";
}
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY $sort_by");

?>

I have another example, which is from a book. It includes the ability to sort ASC or DESC, depending on if they click the top headings, in the table, once or twice. There might be better ways of doing this, but this technique was in a PHP & MySQL book I have, and I've used it and it worked just fine. I altered it somewhat from the book, because I was testing it on a table I had, and I got rid of extra stuff, and this one is only using two links (Make and Model), for sorting, but but you get the idea. You can always add to it, and maybe have the image of an triangle/arrow pointing up or down, depending on which way you're sorting, etc:

Code:
<?php

$link1 = "{$_SERVER['PHP_SELF']}?sort=mfg_a";
$link2 = "{$_SERVER['PHP_SELF']}?sort=model_a";

if(isset($_GET['sort'])){
   switch($_GET['sort']){
      case 'mfg_a':
         $order_by = 'maker ASC';
         $link1 = "{$_SERVER['PHP_SELF']}?sort=mfg_d";
         break;
      case 'mfg_d':
         $order_by = 'maker DESC';
         $link1 = "{$_SERVER['PHP_SELF']}?sort=mfg_a";
         break;
      case 'model_a':
         $order_by = 'model ASC';
         $link2 = "{$_SERVER['PHP_SELF']}?sort=model_d";
         break;
      case 'model_d':
         $order_by = 'model DESC';
         $link2 = "{$_SERVER['PHP_SELF']}?sort=model_a";
         break;
      default:
         $order_by = maker ASC';
         break;
   }
} else {
     $order_by = 'maker ASC';
}

$result = mysql_query("SELECT * FROM the_table ORDER BY $order_by");
if(mysql_num_rows($result) > 0){ ?>
   <table>
     <tr>
       <td><b><a href="<?php echo $link1; ?>">Make</a></b></td>
       <td><b><a href="<?php echo $link2; ?>">Model</a></b></td>
     </tr>
   <?php while ($row = mysql_fetch_array($result)) { ?>
     <tr>
       <td><?php echo $row['maker']; ?></td>
       <td><?php echo $row['model']; ?></b></td>
     </tr>
   <?php }
   echo '</table>';
} else {
   echo "Sorry, there are no items listed at this time.";
}

?>

Hopefully I don't have any big mistakes in that, after doing a quick edit, to shorten it up.
 
Instead of using a switch statement I prefer to use an associative array/hash/dictionary. Using this method you could rewrite Jerome36's top example like so:

Like this:
Code:
<?php
$valid_sorts = array("location"=>"Location",
                     "name"=>"Club_Name",
                     "info"=>"More_Info");
$sortby = isset($valid_sorts[$order]) ? $valid_sorts[$order] : "id";
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY $sort_by");
?>

I've done some things very similar, and like the last example TopGun posted, I've used a switch statement, to check and set values, based on what they clicked to sort. In the switch statement you can also add a default at the end, so even if order equals something other then say the "location," "name," and "info" it'll order by "id" by default.

Another thing to consider, if you do it the way posted with a switch statement, is the possibility of maybe changing the query down the road. The way posted would mean you'd have to edit multiple lines of code, since the query is in each case, in the switch statement. If there are only a few cases it might not be a big deal, but you could do it this way:

Code:
<?php

switch($order) {
   case "location":
      $sort_by = "Location";
      break;
   case "name":
      $sort_by = "Club_Name";
      break;
   case "info":
      $sort_by = "More_Info";
      break;
   default:
      $sort_by = "id";
}
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY $sort_by");

?>
 
I've never seen it done that way before Sgraffite. That's kind of a cool way to do it. Especially if you like less lines of code!
 
Hello,

Sorry about delayed response I have been a bit busy lately, I added the die mysql error code but it didn't change anything.

Any more suggestions on what the problem might be?

AMDbuilder
 
AMDBuilder if you want a really neat way of doing this you should look into stored procedures a.k.a. sprocs. Using the myslqi function set you can store a query in the database and pass different variables to it just like a php function. I can go into more detail but it's pretty late.
 
Hello,

Sorry about delayed response I have been a bit busy lately, I added the die mysql error code but it didn't change anything.

Any more suggestions on what the problem might be?

AMDbuilder

Something must be wrong with the actual query itself. Look at it thoroughly, making sure you have the table and field names correct. The field name you sort by can obviously change, which in your original code could come from the URL, or if not, do a default sort by ID. Looking at what you originally posted, it looks fine as far as the query syntax, but without seeing your database I don't know about the table and field names. I will say that you shouldn't use spaces in your column names (use underscores), and make sure you have the right case for your database, table and columns, when connecting and running queries on the database. I say this because I notice you have your database & table names in lowercase, but your default sort ( ID ) is upper-case.
 
Hello,

Sorry about delayed response I have been a bit busy lately, I added the die mysql error code but it didn't change anything.

Any more suggestions on what the problem might be?

AMDbuilder

make sure the server, db, and user & pass are correct and set.
 
I am a big fan of the KISS theory so I think I will pass on using the sprocs method unless it fits in the KISS theory.

TopGun, that was the first, second, third and Xth thing I checked as I tend to mess that up from time to time, but for once I didn't mess it up...

I have also checked that the database name and table names are all correct along with the column names just in case the spelling got messed up..

To me the error is saying it was able to connect, find the database, find the table, and everything else, but it can't get the data out of the table...

(Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\xampp\htdocs\fccc_beta\affiliated.php on line 90)

Thanks again,
AMDbuilder

Here's the code again direct from the page:
Code:
$order = $_GET['order'];

if ($order = "") {
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY ID") or die(mysql_error());;
}

switch($order) {
case "location":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Location") or die(mysql_error());;

case "name":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Club Name") or die(mysql_error());;

case "info":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY More Info") or die(mysql_error());;
}


				$con = mysql_connect("localhost","root","pass");
					if (!$con)
					{
					die('Could not connect: ' . mysql_error());
					}
					mysql_select_db("table", $con);

					echo '<tr>' . "\n";
						echo '<th class="top" scope="col"><a href="?order=name">Club Name</a></th>' . "\n"; 
						echo '<th class="top" scope="col"><a href="?order=location">Location</a></th>' . "\n";
						echo '<th class="top" scope="col"><a href="?order=info">More Info</a></th>' . "\n";
					echo '</tr>' . "\n";

					while($row = mysql_fetch_array($result))
                       {
					echo '<tr>' . "\n";
							echo '<td>' . $row['Club Name'] . '</td>' . "\n";
							echo '<td>' . " " . $row['Location'] . '</td>' . "\n";
							echo '<td>' . " " . $row['More Info'] . '</td>' . "\n";
					echo '</tr>' . "\n";
						}

					mysql_close($con);
 
It might be the program flow, it looks like you are:

1. Trying to query the DB
2. Then connecting to the DB
3. Then selecting a table in the DB
4. Then trying to select results from the query
5. Finally closing the connection.

I'm thinking #1 should be after #3

I am a big fan of the KISS theory so I think I will pass on using the sprocs method unless it fits in the KISS theory.

TopGun, that was the first, second, third and Xth thing I checked as I tend to mess that up from time to time, but for once I didn't mess it up...

I have also checked that the database name and table names are all correct along with the column names just in case the spelling got messed up..

To me the error is saying it was able to connect, find the database, find the table, and everything else, but it can't get the data out of the table...

(Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\xampp\htdocs\fccc_beta\affiliated.php on line 90)

Thanks again,
AMDbuilder

Here's the code again direct from the page:
Code:
$order = $_GET['order'];

if ($order = "") {
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY ID") or die(mysql_error());;
}

switch($order) {
case "location":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Location") or die(mysql_error());;

case "name":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Club Name") or die(mysql_error());;

case "info":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY More Info") or die(mysql_error());;
}


				$con = mysql_connect("localhost","root","pass");
					if (!$con)
					{
					die('Could not connect: ' . mysql_error());
					}
					mysql_select_db("table", $con);

					echo '<tr>' . "\n";
						echo '<th class="top" scope="col"><a href="?order=name">Club Name</a></th>' . "\n"; 
						echo '<th class="top" scope="col"><a href="?order=location">Location</a></th>' . "\n";
						echo '<th class="top" scope="col"><a href="?order=info">More Info</a></th>' . "\n";
					echo '</tr>' . "\n";

					while($row = mysql_fetch_array($result))
                       {
					echo '<tr>' . "\n";
							echo '<td>' . $row['Club Name'] . '</td>' . "\n";
							echo '<td>' . " " . $row['Location'] . '</td>' . "\n";
							echo '<td>' . " " . $row['More Info'] . '</td>' . "\n";
					echo '</tr>' . "\n";
						}

					mysql_close($con);
 
It might be the program flow, it looks like you are:

1. Trying to query the DB
2. Then connecting to the DB
3. Then selecting a table in the DB
4. Then trying to select results from the query
5. Finally closing the connection.

I'm thinking #1 should be after #3

Yup, I think you're right. The queries are being run, in the switch statement, before you call the code to connect to, and pick the database. I'd also recommend adding breaks at the end of each case, in the switch statement, because without them, even if it finds a case that is true, without a break, it will check any other cases, until it gets to the end of the switch statement, even if it doesn't have to anymore.
 
Hey,

I tried moving the connection lines up, but that didn't seam to help so I added the breaks as suggested. I think I got the breaks right, but I havn't used them before so I could have that messed up as well...

Code:
            <?php
$order = $_GET['order'];

$con = mysql_connect("localhost","root","aaaaaa");
					if (!$con)
					{
					die('Could not connect: ' . mysql_error());
					}
					mysql_select_db("table", $con);

if ($order = "") {
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY ID") or die(mysql_error());
break;
}

switch($order) {
case "location":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Location") or die(mysql_error());
break;

case "name":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Club Name") or die(mysql_error());
break;

case "info":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY More Info") or die(mysql_error());
break;
}

					echo '<tr>' . "\n";
						echo '<th class="top" scope="col"><a href="?order=name">Club Name</a></th>' . "\n"; 
						echo '<th class="top" scope="col"><a href="?order=location">Location</a></th>' . "\n";
						echo '<th class="top" scope="col"><a href="?order=info">More Info</a></th>' . "\n";
					echo '</tr>' . "\n";

					while($row = mysql_fetch_array($result))
                       {
					echo '<tr>' . "\n";
							echo '<td>' . $row['Club Name'] . '</td>' . "\n";
							echo '<td>' . " " . $row['Location'] . '</td>' . "\n";
							echo '<td>' . " " . $row['More Info'] . '</td>' . "\n";
					echo '</tr>' . "\n";
						}

					mysql_close($con);
			?>
 
A couple things involving your if statement. Number one, get rid of the break in the if statement. You just need those in your switch statement. Secondly, you're missing an '=' sign, when checking $order:

So this:
Code:
if ($order = "") {
     $result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY ID");
     break;
}

Becomes this:
Code:
if ($order == "") {
     $result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY ID");
}

Next do one of these two things. The first choice is after the if statement add an else. Because as it stands with the code you have now, you check the if statement, and even if it's TRUE, it's going to run the switch statement. If 'order' equals NULL and you do the default query, there's no point in running the other tests in the switch. So you could change it to this:

Code:
if ($order == "") {
     $result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY ID") or die(mysql_error());
     break;
} else {
     switch($order) {
        case "location":
             $result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Location");
             break;
        case "name":
             $result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Club Name");
             break;
        case "info":
             $result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY More Info");
             break;
     }
}

Or you could get rid of the if statement all-together and create a default case at the end of the switch statement, that would do the "ORDER BY ID" if none of the cases were true.

Are you getting the same error no matter what query you're running? Whether you're doing the "ORDER BY ID," "ORDER BY Location," etc? The reason I ask this is because I expect the "ORDER BY ID" and "ORDER BY Location" ones to work. Your other two ("Club Name" and "More Info") I'd think would cause errors. Unless the newer versions of mysql have changed (since I first learned it), you shouldn't have table and column names with spaces in them.
 
Dang I think this code hates me! Still no go...

I also shortened the column names in case that might be the problem..

AMDbuilder

Code:
            <?php
$order = $_GET['order'];

$con = mysql_connect("localhost","root","aaaaaaaaaa");
					if (!$con)
					{
					die('Could not connect: ' . mysql_error());
					}
					mysql_select_db("aaaaaaaaaa", $con);

if ($order = "") {
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY ID") or die(mysql_error());
}
else {
switch($order) {
case "location":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Location");
break;

case "name":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Name");
break;

case "info":
$result = mysql_query("SELECT * FROM affiliated_club_list ORDER BY Info");
break;
}
}

					echo '<tr>' . "\n";
						echo '<th class="top" scope="col"><a href="?order=name">Club Name</a></th>' . "\n"; 
						echo '<th class="top" scope="col"><a href="?order=location">Location</a></th>' . "\n";
						echo '<th class="top" scope="col"><a href="?order=info">More Info</a></th>' . "\n";
					echo '</tr>' . "\n";

					while($row = mysql_fetch_array($result))
                       {
					echo '<tr>' . "\n";
							echo '<td>' . $row['Club Name'] . '</td>' . "\n";
							echo '<td>' . " " . $row['Location'] . '</td>' . "\n";
							echo '<td>' . " " . $row['More Info'] . '</td>' . "\n";
					echo '</tr>' . "\n";
						}

					mysql_close($con);
			?>
 
Are you still getting the same error as before? Be sure to add the extra '=' sign inside your if statement. I noticed I forgot to add it myself, to the final code window I had in my last post. Anyway, after the closing bracket on the else, and before you begin to echo your results, put this in:

Code:
if (!$result) {
    $message = 'Invalid Query: '.mysql_error()."<br>\n";
    die($message);
}

When you run the page do you get anything involving this "Invalid query" error? I quickly made some changes, to actually show which query is being run, if there is an error, but I may have missed something. It's late.

Code:
<?php

$con = mysql_connect("localhost","root","aaaaaaaaaa");
if (!$con){
     die('Could not connect: ' . mysql_error());
}
mysql_select_db("aaaaaaaaaa", $con);

$order = $_GET['order'];
switch($order){
     case "location":
          $query = "SELECT * FROM affiliated_club_list ORDER BY Location";
          break;
     case "name":
          $query = "SELECT * FROM affiliated_club_list ORDER BY Name";
          break;
     case "info":
          $query = "SELECT * FROM affiliated_club_list ORDER BY Info";
          break;
     default:
          $query = "SELECT * FROM affiliated_club_list ORDER BY ID";
}

$result = mysql_query($query);
if(!$result){
     $message  = 'Invalid query: ' . mysql_error() . "<br>\n";
     $message .= 'Whole query: ' . $query;
     die($message);
}

echo '<tr>' . "\n";
echo '<th class="top" scope="col"><a href="?order=name">Club Name</a></th>' . "\n"; 
echo '<th class="top" scope="col"><a href="?order=location">Location</a></th>' . "\n";
echo '<th class="top" scope="col"><a href="?order=info">More Info</a></th>' . "\n";
echo '</tr>' . "\n";

while($row = mysql_fetch_array($result)){
     echo '<tr>' . "\n";
     echo '<td>' . $row['Club Name'] . '</td>' . "\n";
     echo '<td>' . " " . $row['Location'] . '</td>' . "\n";
     echo '<td>' . " " . $row['More Info'] . '</td>' . "\n";
     echo '</tr>' . "\n";
}

mysql_close($con);

?>
 
Doa! I missed the extra = in the if statement...

Problem solve! Thanks for all the help!
AMDbuilder
 
Back
Top