我只是想通过ID对评论进行排序,但我没有运气。无法弄清楚该怎么做,因为这让我很困惑:articleid='" . mysql_real_escape_string($_GET['id']) . "'
你们是否碰巧知道如何通过DESC中的id订购评论?谢谢!
<?php
$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'"); $comments = mysql_num_rows($amount_get);
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'");
if (mysql_num_rows($grab)==0) {
echo "<div class='alert alert-note-x'>Sorry, it looks like their are no comments to be displayed, check back later!</div>";
}
while($row = mysql_fetch_array($grab)){
?>
答案 0 :(得分:5)
首先,你要做两次相同的SELECT
次。这是非常不必要的,因为您可以计算行并从单个查询中获取数据。除此之外,还可以使用评论表的唯一ID替换commentid
并进行设置。将DESC
替换为ASC
以反转排序顺序。
<?php
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "' ORDER BY commentid DESC");
$comments = mysql_num_rows($grab);
if (mysql_num_rows($grab)==0) {
echo "<div class='alert alert-note-x'>Sorry, it looks like their are no comments to be displayed, check back later!</div>";
}
while($row = mysql_fetch_array($grab)){
?>
答案 1 :(得分:1)
添加ORDER BY
子句
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "' ORDER BY articleid, ID DESC");
您的查询容易被SQL Injection
攻击,请阅读以下文章以防止它,
答案 2 :(得分:0)
试试这个
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "' order by articleid desc");
答案 3 :(得分:0)
我认为你的评论表后面有一列id
,所以:
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "' ORDER BY id DESC");
这是一个sql的东西来排序它,而不是php,所以你只需要修改你的sql语句。
答案 4 :(得分:0)
$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "' ORDER BY id DESC ");
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "' ORDER BY id DESC");
答案 5 :(得分:0)
三点建议:
1)在字符串变量中完成“select”语句(如下所示;它使调试更容易)
2)考虑使用预准备语句而不是原始“select”(或更新或删除!)。
它可以帮助提高性能。但它使您的PHP 更多更安全!
3)考虑远离(不推荐使用的)mysql_query()语法
<?php
$sql =
"SELECT * FROM comment WHERE articleid='" .
mysql_real_escape_string($_GET['id']) . "' order by articleid desc";
$amount_get = mysql_query($sql);
$comments = mysql_num_rows($amount_get);
$sql =
"SELECT * FROM comment WHERE articleid='" .
mysql_real_escape_string($_GET['id']) . "'order by articleid desc";
$grab = mysql_query($sql);
...
这是mySQLi和PDI API上的一个很好的链接,它取代了旧的mysql_query()语法:
这是预备陈述的良好链接:
答案 6 :(得分:0)
您可以在查询中使用order by子句
<?php
$getarticles = array();
$getarticles = mysql_query("SELECT * FROM comment order by articleid desc");
if(empty($getarticles)){
echo "<div class='alert alert-note-x'>Sorry, it looks like their are no comments to be displayed, check back later!</div>";
}
echo "<pre>";
print_r($getarticles);
echo "</pre>";
for($i=0;$i<count($getarticles);$i++){
//display
}
?>