以特定順序顯示從mysql db檢索到的數據我試圖按照特定順序顯示問題,以及特定順序的NOT ASC或DESC,但是由「question_order」列定義。如何使用php
我有一個MySQL數據庫下表:
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」是每個用戶唯一的,在分貝作爲管道分隔列表。 (即:85 | 41 | 58 | 67 | 21 | 8 | 91 | 62等)
PHP版27年3月5日
如果此整個過程可以使用完全不同的方法來實現更好,然後請告訴我。
我的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";
}
的問題清單已經被這問題mumbers的管道分隔列表中的question_order進行排序,像45 | 87 | 65 | 85 | 14 | 7 | 62 | ...等。不是DESC或ASC。 – Mark
問題是你不能使用簡單的'ORDER BY' SQL子句,因爲你沒有規範化的數據庫,不是嗎?修復數據庫設計是否太晚了?否則,你的數據庫不會比在普通文件中存儲東西更有幫助。 –
@ÁlvaroG.Vicario我不這麼認爲,但我不是專家:)我只需要按照「question_order」列中指定的順序列出問題以及答案。 「question_order」列中的數字與問題編號相關。 – Mark