根据html <select> choice?</select>重新排序mysql结果

时间:2014-05-27 13:03:01

标签: php html mysql

另一个可能是愚蠢的问题......我有一个数据库来检查网页上的项目。我也有基于mysql表数据在我的页面上填充表的评论。

我想做什么,而且我在线搜索但未设法找到解决方案,是根据我的html下拉菜单上的选择重新排序代码。

有什么建议吗?

现在的代码。如果需要更多,我可以提供。

    <p>Order By: <select>
  <option value="newest" id="newest">Newest First</option>
  <option value="oldest" id="oldest">Oldest First</option>
  <option value="highest" id="highest">Highest Rating</option>
  <option value="lowest" id="lowest">Lowest Rating</option>
</select></p>

<?php
include "common.php";

mysql_connect("HOST", "USER", "PASS") or die(mysql_error());
mysql_select_db("DB") or die(mysql_error());
 $sql = "SELECT email, review, rating FROM reviews ORDER BY review_id DESC ";
  $result = mysql_query($sql)or die(mysql_error());

  echo "<table>";
  echo "<tr><th>User</th><th>&nbsp&nbsp&nbsp</th><th>Review</th><th>&nbsp&nbsp&nbsp</th><th>Rating</th></tr>";

  while($row = mysql_fetch_array($result)){
    $email     = $row['email'];
    $review    = $row['review'];
    $rating    = $row['rating'];

echo "<tr>
  <td>".$email."</td>
  <td></td>
  <td>".$review."</td>
  <td></td>
  <td>".$rating."</td>
  </tr>";
}
?>  

2 个答案:

答案 0 :(得分:0)

<p>Order By: 
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="GET">
    <select name="ordering">
      <option value="pk DESC" id="newest">Newest First</option>
      <option value="pk ASC" id="oldest">Oldest First</option>
      <option value="rating DESC" id="highest">Highest Rating</option>
      <option value="rating ASC" id="lowest">Lowest Rating</option>
    </select>
</form>
</p>

<?php
include "common.php";

mysql_connect("HOST", "USER", "PASS") or die(mysql_error());
mysql_select_db("DB") or die(mysql_error());
if(isset($POST['ordering'])) { 
    $sql = "SELECT email, review, rating FROM reviews ORDER BY" . $POST['ordering'];
} else {
     $sql = "SELECT email, review, rating FROM reviews ORDER BY review_id DESC ";
}
 $result = mysql_query($sql)or die(mysql_error());

  echo "<table>";
  echo "<tr><th>User</th><th>&nbsp&nbsp&nbsp</th><th>Review</th><th>&nbsp&nbsp&nbsp</th><th>Rating</th></tr>";

  while($row = mysql_fetch_array($result)){
    $email     = $row['email'];
    $review    = $row['review'];
    $rating    = $row['rating'];

echo "<tr>
  <td>".$email."</td>
  <td></td>
  <td>".$review."</td>
  <td></td>
  <td>".$rating."</td>
  </tr>";
}
?>  

您需要做的就是将select包装在提交给自己的form中,将option值更改为部分SQL查询,最后根据条件生成SQL语句形式输入。

答案 1 :(得分:0)

您必须以某种方式将所选值传递给php: - 通过POST或GET,提交表格或通过ajax

然后您需要根据该值进行排序,并将结果返回到屏幕。

我假设您是PHP的新手,所以我建议您阅读有关PDO,mysqli或其他一些连接到数据库的框架,因为不推荐使用mysql_ *函数,并在放入之前正确清理字符串它在查询上。