如何按降序显示 Ajax 结果?



嗨,我有一个ajax代码,它能够按升序从sql表中获取数据。

这是主要的.php

<?php  
$connect = mysqli_connect("localhost", "admin", "", "main");
$sql = "SELECT * FROM names LIMIT 8";  
$result = mysqli_query($connect, $sql);  
$id = '';  
?>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
<div class="table-responsive"> 
<table class="table table-bordered" id="load_data_table">  
<?php  
while($row = mysqli_fetch_array($result))  
{  
?>  
<tr>  
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["name"]; ?></td>  
</tr>  
<?php  
$id = $row["id"];  
} 
?>  
<tr id="remove_row">  
td><button type="button" name="btn_more" data-id="<?php echo $id; ?>" id="btn_more" class="btn btn-success form-control">more</button></td>  
</tr>  
</table>  
</div>           
<script>  
$(document).ready(function(){  
$(document).on('click', '#btn_more', function(){  
var last_id = $(this).data("id");  
$('#btn_more').html("Loading...");  
$.ajax({  
url:"resources/views/frontend/ajax/one.php",  
method:"POST",  
data:{last_id:last_id},  
dataType:"text",  
success:function(data)  
{  
if(data != '')  
{  
$('#remove_row').remove();  
$('#load_data_table').append(data);  
}  
else  
{  
$('#btn_more').html("No Data");  
}  
}  
});  
});  
});  
</script>

这是其中之一.php

<?php  
$output = '';  
$id = '';  
sleep(1);  
$connect = mysqli_connect("localhost", "admin", "", "main");
$sql = "SELECT * FROM names WHERE id > ".$_POST['last_id']." LIMIT 8";  
$result = mysqli_query($connect, $sql);  
if(mysqli_num_rows($result) > 0)  
{  
while($row = mysqli_fetch_array($result))  
{  
$id = $row["id"];  
$output .= '  
<tbody>  
<tr>  
<td>'.$row["id"].'</td> 
<td>'.$row["name"].'</td> 
</tr></tbody>';  
}  
$output .= '  
<tbody><tr id="remove_row">  
<td><button type="button" name="btn_more" data-id="'. $id .'" id="btn_more" class="btn btn-success form-control">more</button></td>  
</tr></tbody>  
';  
echo $output;  
}  
?>

我的 sql 表有两列 id 和名称。

此代码非常适合升序,即如果"id"的值正在增加(1,2,3...(

我已经尝试了 SQL 语句中的 ORDER BY 子句,但没有运气。

我想按降序显示数据,即首先显示最高的"id"值。

请帮忙。

您应该使用Order By子句。这有助于对结果进行排序。

按如下所示修改查询:

$sql = "SELECT * FROM names ORDER BY id DESC LIMIT 8";  

您确实应该考虑学习PDO,因为您的第二个查询可能会注入SQL。

最新更新