如何使用php以特定顺序显示从mysql db检索的数据

时间:2014-06-22 09:03:54

标签: php mysql arrays usort

我正在尝试显示问题,以及用户按特定顺序回答,不是ASC或DESC,而是按照" question_order"列。

我在mysql db中有以下表格:

questions (qid, question_text)
answers   (aid, uid, answer)
usermeta  (userid, question_order)

"questions" table contains the questions
"answers" table contains every users answers to all questions
"usermeta" table contains the sort order for the questions in "question_order".

" question_order"每个用户都是唯一的,并且在db中作为管道分隔列表。 (即:85 | 41 | 58 | 67 | 21 | 8 | 91 | 62等)

PHP Version 5.3.27

如果使用完全不同的方法可以更好地完成整个过程,请告诉我。

我的PHP能力有限。话虽如此,下面是我玩了几个小时后的那一刻......

    $sql = "
        SELECT
                *
        FROM
                ".USERMETA_TABLE."
        WHERE
                userid = {$userid}
    ";

    $result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
    $row = $result->fetch_assoc();

    $order_array = explode('|', $row['question_order']);

    $sql = "
        SELECT
                *
        FROM
                ".QUESTIONS_TABLE."
    ";

    $result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
    $row = $result->fetch_assoc();


    // my attempt at sorting the questions. the $order_array 
    // does not have a unique id so I am kind of lost as to 
    // how to make this work

    usort($myArray, function($order_array, $row) {
        return $order_array - $row['qid'];
    });


    $sql = "
        SELECT
                *
        FROM
                ".QUESTIONS_TABLE."
    ";

    $result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);

    while ( $row = $result->fetch_assoc() )
    {
        $sql = "
            SELECT
                    *
            FROM
                    ".ANSWERS_TABLE."
            WHERE
                    uid = {$userid}
                AND
                    qid = ".$row['qid']."
            LIMIT
                    1
        ";

        $result2 = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
        $row2 = $result2->fetch_assoc();

        echo '      <p>'.$row['question_text'].'</p>'."\n";
        echo '      <p>'.$row2['answer'].'</p>'."\n";
    }

3 个答案:

答案 0 :(得分:1)

从db中检索时过滤掉数据。

使用: - SELECT * FROM [TABLE_NAME] ORDER BY qid DESC

然后在PHP中,您可以使用会话变量并相应地修改值。

答案 1 :(得分:0)

如果您想使用ID订购,可以使用

SELECT * FROM [TABLE_NAME] ORDER BY qid DESC

这将按降序排序如果您想按升序使用ASC

答案 2 :(得分:0)

我继续通过添加一个表来存储问题编号,用户排序顺序和学生用户ID来更改数据库:

student_id, sort_order, question_id
1               1               8
1               2               2
1               3               97

然后能够使用以下语句选择它:

SELECT q.* 
FROM 
questions q
JOIN questions_sorting_order qso
ON q.id = qso.question_id
ORDER BY qso.sort_order
WHERE qso.student_id = $student_id

......效果很好。

感谢FuzzyTree对此的帮助:How do I sort data from a mysql db according to a unique and predetermined order, NOT asc or desc