以特定顺序显示从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