MySQL查询从两个表中获取问卷的答复

时间:2017-09-23 20:21:17

标签: php mysql

这里不堪重负的菜鸟。我将不胜感激任何帮助。我已经在这方面工作了几天而且正在破解。

我有两个表格,问题和结果:

表 - 问题:

ID   |questions            |ans1     |ans2     |ans3     |ans4 
-----|---------------------|---------|---------|---------|---------
1    | Favorite color:     |red      |blue     |green    |purple
2    | Favorite animal:    |cat      |dog      |snake    |bird
3    | Favorite food:      |pizza    |hotdog   |chicken  |salad

表 - 结果:

ID   |user_id    |ques1  |ques2  |ques3
-----|-----------|-------|-------|-----
122  |abc123     |   1   |   3   |  4
123  |xyz987     |   3   |   3   |  1  
124  |ghj567     |   4   |   1   |  1  

user_id abc123的所需输出表:

ques|question         |ques_value|response
1   |Favorite color:  |     1    |  red 
2   |Favorite animal: |     3    |  snake
3   |Favorite food:   |     4    |  salad

不能选择更改表的结构。

请帮助!!

1 个答案:

答案 0 :(得分:0)

既然你说更改表结构不是一个选项,我将不再讨论关系数据库。

$conn = new mysqli($servername, $username, $password, $database);

$sql= "SELECT * FROM TABLE results WHERE user_id='abc123'";

$result = $conn->query($sql);

if($result->num_rows >0){
        $output=array();
        $row = $result->fetch_assoc();

        while($row=$result->fetch_assoc()){
            array_push( $output, $row['ques1'], $row['ques2'], $row['ques3'] );
        }

/*All of this will get the answers from the user. You now have two options, either hardcode
the answer and the word it references, or make another request to the database*/

选项1

将此代码添加到您的程序

switch($output[0]){//Use a switch statement on the first question
    case "ans1":
        $ans1='red';
        break;
    //Continue this for all answers and questions
}

选项2(如果数据库可能更改,则更好)

将此代码添加到您的程序

$ conn = new mysqli($ servername,$ username,$ password,$ database);

$sql= "SELECT * FROM TABLE questions";

$result = $conn->query($sql);

if($result->num_rows >0){
        $row = $result->fetch_assoc();

        while($row=$result->fetch_assoc()){

            $outputText=array();

            foreach($output as $value){//Loop through all questions
                switch($value){//Use switch statement to match answer number and answer text
                    case 1:
                        array_push($outputText,$row['ans1']);
                        break;
                    case 2:
                        array_push($outputText,$row['ans2']);
                        break;
                    case 3:
                        array_push($outputText,$row['ans3']);
                        break;
                    case 4:
                        array_push($outputText,$row['ans4']);
                        break;
                }
            }
        }

这应该为您提供$outputText[]数组中所需的一切。

最后,祝你好运,我希望这会有所帮助。