链接到PHP MYSQL中的排序表列

链接到PHP MYSQL中的排序表列

问题描述:

<?php
$con = mysql_connect ("localhost", "user", "pass") 
  or die ('Error: ' . mysql_error());
mysql_select_db ("members");

if(isset($_GET['orderby'])){ 
$order = $_GET['orderby']; 
$result = "SELECT * FROM persons ORDER BY ".mysql_real_escape_string($order)." DESC"; 
}
else{
$result = mysql_query("select * from persons");
}

$num_rows = mysql_num_rows($result);
$row_counter = 0; 

echo "<table width=600 border=0 cellspacing=0>
";
echo "<tr>

      <th>&nbsp;</th>

      <th>First Name</th>

      <th>Last Name</th>

      <th>Email Address</th>

      <th>City</th>

      <th>State</th>

      <th><a href='index.php?orderby=submitDate'>Date</a></th>

      </tr>";

while($row = mysql_fetch_array($result)){
  if($row_counter % 2){
    $row_color="bgcolor='#FFFFFF'";
  }
  else{
    $row_color="bgcolor='#F3F6F8'";
  }
  echo "<tr ".$row_color.">";
  echo "<td class='id'>" . $row['id'] . "</td>
";
  echo "<td>" . $row['firstName'] . "</td>
";
  echo "<td>" . $row['lastName'] . "</td>
";
  echo "<td>" . $row['email'] . "</td>
";
  echo "<td>" . $row['city'] . "</td>
";
  echo "<td>" . $row['state'] . "</td>
";
  echo "<td>" . $row['submitDate'] . "</td>
";
  echo "</tr>";
  $row_counter++;
  }
echo "</table>";

mysql_close($con);
?

>

I just cannot figure out why my link to sort my query is not working. any ideas? Pre-Thanks!

Your if else block was wrong. In one case $result is a query in another it is a result-set. Check code below.. fixed.

<?php
$con = mysql_connect ("localhost", "user", "pass") 
  or die ('Error: ' . mysql_error());
mysql_select_db ("members");

if(isset($_GET['orderby'])){ 
$order = $_GET['orderby']; 
$sql = "SELECT * FROM persons ORDER BY ".mysql_real_escape_string($order)." DESC"; 
}
else{
$sql = "select * from persons";
}
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$row_counter = 0; 

echo "<table width=600 border=0 cellspacing=0>
";
echo "<tr>

      <th>&nbsp;</th>

      <th>First Name</th>

      <th>Last Name</th>

      <th>Email Address</th>

      <th>City</th>

      <th>State</th>

      <th><a href='index.php?orderby=submitDate'>Date</a></th>

      </tr>";

while($row = mysql_fetch_array($result)){
  if($row_counter % 2){
    $row_color="bgcolor='#FFFFFF'";
  }
  else{
    $row_color="bgcolor='#F3F6F8'";
  }
  echo "<tr ".$row_color.">";
  echo "<td class='id'>" . $row['id'] . "</td>
";
  echo "<td>" . $row['firstName'] . "</td>
";
  echo "<td>" . $row['lastName'] . "</td>
";
  echo "<td>" . $row['email'] . "</td>
";
  echo "<td>" . $row['city'] . "</td>
";
  echo "<td>" . $row['state'] . "</td>
";
  echo "<td>" . $row['submitDate'] . "</td>
";
  echo "</tr>";
  $row_counter++;
  }
echo "</table>";

mysql_close($con);
?>