dongqiao8417 2015-04-10 20:32
浏览 45
已采纳

在php中排序mysql结果

When I use the following code:

$result = queryMysql("SELECT * FROM games ORDER BY game ASC");
$num    = $result->num_rows;

for ($j = 0 ; $j < $num ; ++$j)
{

        $row = $result->fetch_array(MYSQLI_ASSOC);
        echo "<input type='checkbox' name='game' value='$row['id']'>$row['game']<br>";
}

the result is not shown alphabetically. it has Destiny first, and Battlefield last. Destiny has ID 1, and Battlefield has ID 11.

Why isn´t it being sorted? If I use the command in PhpMyAdmin I get the list back sorted.

(Sorry if this is too simple, but I didn´t find any solutions here. All refered to use ORDER BY, but that´s not working).

From MyPhpAdmin

From Webpage

New code changed to:

$result = queryMysql("SELECT * FROM games ORDER BY game ASC");

while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
    echo "<input type='checkbox' name='game' value='$row['id']'>$row['game']<br>";
}

Still not working. Could this be a server error?

Not sure what happened here, but after 8 hours of sleep and I reload the page, it´s sorting as it should (still using Maximus2012´s example). I guess it must have been a server glitch, since I didn´t change the code while sleeping.

I´ll give creds to Maximus2012 for his quick and good responds! (and thanks to all others too ofcourse!)

  • 写回答

3条回答 默认 最新

  • douyue3800 2015-04-10 20:37
    关注

    Replace this :

    $num    = $result->num_rows;
    for ($j = 0 ; $j < $num ; ++$j)
    {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        echo "<input type='checkbox' name='game' value='$row['id']'>$row['game']<br>";
    }
    

    with this: (get rid of $num and the for loop)

    while ($row = $result->fetch_array(MYSQLI_ASSOC))
    {
         echo "<input type='checkbox' name='game' value='$row['id']'>$row['game']<br>";
    }
    

    and see if that works. You don't need for loop since you are not using the $j variable anywhere anyway. This answer is based on the assumption that your MySQL query is giving you correct result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题