Php 如何在mysql中使用order和between
我在mysql代码中使用Order和Between时遇到问题:Php 如何在mysql中使用order和between,php,mysql,sql-order-by,between,Php,Mysql,Sql Order By,Between,我在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)
<?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降序排列
请帮助我那么您想先输入id最高的条目吗?那么应该是这样的:
Select * from my_data where id between ($id+1) and ($id+4) ORDER BY id DESC
$query=“从my_数据中选择*,其中id介于($id+1)和($id+4)之间,按id描述排序”
注意处理查询时的SQL注入方式 试试这个
<?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
参数,如果未设置该参数,则它将给出降序,否则将其设置为&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
输出描述
首先,请访问了解SQL注入以及如何防止SQL注入。对于订单内容:
orderbyid DESC
从my_数据中选择*,其中id介于($id+1)和($id+4)orderbyid DESC
-您也可以从DESC更改为ASC