且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用ORDER BY或PHP排序功能对MySQL查询进行排序

更新时间:2023-11-23 16:31:10

感谢您的所有帮助人员,但是您的回答都没有让我对数据进行排序,并在排序后将其正确地回送到HTML表中. UNION可能有用,但是我认为我的解决方案要想尽办法就可以了.

Thanks for all your help guys, but none of your answers allowed me to sort the data AND echo it into the HTML table correctly once sorted. A UNION might have worked, but I think my solution was faster as far as figuring it all out goes.

                $query = "SELECT c_id, b_name, l_name, f_name, phone FROM customers";
                $result = mysql_query($query);
                mysql_close($link);

                $num = mysql_num_rows($result);

                for ($i = 0; $i < $num; $i++){
                    $row = mysql_fetch_array($result);

                    if($row[b_name]!=''){
                        $new_result[$i]['c_id'] = $row[c_id];
                        $new_result[$i]['c_name'] = $row[b_name];
                        $new_result[$i]['phone'] = $row[phone];
                    }

                    else{
                        $new_result[$i]['c_id'] = $row[c_id];
                        $new_result[$i]['c_name'] = $row[l_name].", ".$row[f_name];
                        $new_result[$i]['phone'] = $row[phone];                         
                    }
                }                       

                foreach ($new_result as $key => $row) {
                   $c_id[$key]  = $row['c_id'];
                   $c_name[$key] = $row['c_name'];
                   $phone[$key] = $row['phone'];
                }

                array_multisort($c_name, SORT_ASC, $c_id, SORT_ASC, $new_result);   

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

                    $class = (($i % 2) == 0) ? "table_odd_row" : "table_even_row";

                    echo "<tr class=".$class.">";

                        echo "<td><a href=Edit_Customer.php?c_id=".$new_result[$i]['c_id'].">".$new_result[$i]['c_id']."</a></td>";
                        echo "<td><a href=Edit_Customer.php?c_id=".$new_result[$i]['c_id'].">".$new_result[$i]['c_name']."</a></td>";
                        echo "<td><a href=Edit_Customer.php?c_id=".$new_result[$i]['c_id'].">".$new_result[$i]['phone']."</a></td>";

                    echo "</tr>";                       

                }

            ?>      

        </table>