如何在mysql中使用order和between

n1bvdmb6  于 2021-06-21  发布在  Mysql
关注(0)|答案(4)|浏览(466)

我在mysql代码中使用order和between时遇到问题:

<?php 

$connection = mysqli_connect("localhost","my_user","my_password","my_db");
$id = $_GET["id"];
$query = "Select * from my_data where id between ($id+1) and ($id+4)";
$result = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($result)) {

    $array[] = $row;    
}
header('Content-Type:Application/json');
echo json_encode($array);?>

我想按id降序输出请帮助我

voj3qocg

voj3qocg1#

$query=“从我的\u数据中选择*,其中id介于($id+1)和($id+4)之间,order by id desc”;
在处理查询时要小心sql注入!

8i9zcol2

8i9zcol22#

试着用这个。

<?php 
$connection = mysqli_connect("localhost","my_user","my_password","my_db");
$id = $_GET["id"];
$query ="";
$query.= "Select * from my_data where id between ($id+1) and ($id+4)";
$query.= " order by id DESC"; //concat query as per requirement. 
$result = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($result)) {

    $array[] = $row;    
}
header('Content-Type:Application/json');
echo json_encode($array);
?>

还可以通过在变量上设置按字段名和按类型(asc/desc)动态传递order。请随时询问任何关于它的问题。

kyks70gy

kyks70gy3#

让我们试试这个:
我加了一个额外的 order 参数如果未设置,则将按降序排列,否则将设置为 &order=asc 用于加入订单结果。订购是在 id 在野外。
更新数据库连接设置

<?php 

   //kindly change connection parameter as per you need
    $connection = mysqli_connect("localhost","root","","test");
   $id = $_GET["id"];

   isset( $_GET['order']) ? $order =$_GET['order'] : $order= 'desc';

   if($order === 'asc'){
       $query = "Select * from person where id between ($id+1) and ($id+4) order by id asc";
   }else{
       $query = "Select * from person where id between ($id+1) and ($id+4) order by id desc";
   }

  $result = mysqli_query($connection,$query);
 while ($row = mysqli_fetch_assoc($result)) {
    $array[] = $row;    
 }
 header('Content-Type:Application/json');

    echo json_encode($array);
?>

请注意url

输出asc

输出描述

vptzau2j

vptzau2j4#

所以你想先找到id最高的条目?那么应该是这样的:

Select * from my_data where id between ($id+1) and ($id+4) ORDER BY id DESC

相关问题