在MySQL语句中使用下拉和变量排序(PHP)

时间:2013-11-27 14:58:17

标签: php mysql sorting mysqli

我正在尝试使用下拉菜单对结果进行排序。我想从下拉列表中获取一个值,并通过将其分配给变量将其输入到MySQL语句中。我尝试了一些没有成功的事情。有任何想法吗?谢谢。之前我可以从表中提取数据并正确显示。这只是排序问题。

<form name="order" method="post">
                          <select name='order'>
<option value='ORDER BY product_name ASC'>A-Z
<option value='ORDER BY product_name DSC'>Z-A
<input type="submit" value="Submit"  />
                        </select>
                        </form> 

       <div id="Products">
          <p>
            Products:
          </p><?php
              $con=mysqli_connect("localhost","root","","db_tc");
          // Check connection

         $order=$_POST['order'];

              if (mysqli_connect_errno())
              {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
              }
              $result = mysqli_query($con,"SELECT * FROM tbl_products ORDER BY $order");



              while($row = mysqli_fetch_array($result))
              {
                echo "<div id='item'>";
                echo "<div id= 'pic'><img class='pic' src='". $row['product_img'] . "'/></div>";
                echo "<div id= 'itemname'><h1> <a href=\"product.php?id=". $row['product_id'] ."\">" . $row['product_name'] . "</h1></a></div>";
                echo "<div id= 'price'> <h2>Price:</h2><br>£" . $row['product_price'] . "</div>";
                echo "<div id= 'signed'> <h2>Signed:</h2><br>" . $row['product_signed'] . "</div>";
                echo "<div id= 'type'> <h2>Type:</h2><br>" . $row['product_type'] . "</div>";

                echo "</div>";
              }
              echo "</table>";

              mysqli_close($con);
              ?>
        </div>

1 个答案:

答案 0 :(得分:0)

您使用$ _POST字段发送的值是“ORDER BY name ASC”,并且您尝试将其添加到已包含“ORDER BY”子句的sql语句中,这可能是您的问题。我猜这是“DESC”而不是“DSC”

您是否考虑过,如果有人在select字段的值中添加了单引号并将其发布,会发生什么?您应该始终转义从用户收到的值。如果你也使用准备好的陈述,那就更好了。