Как получить 1 вопрос и 4 ответа из этого сценария? - PullRequest
2 голосов
/ 27 марта 2019

Я создаю игру webGL для Unity, но сначала хочу правильно настроить php.

У меня есть 2 таблицы вопросов и ответов. На каждый вопрос есть 4 возможных ответа, и мне нужно получить их из моей базы данных. Таблица ответов совпадает с таблицей вопросов через questionId.

Вопросы:

  • Должен ли я лучше использовать объединение таблиц или я должен их разделить?
  • Должен ли я просто выбрать оператор только для таблицы вопросов, тогда присоединиться к таблице ответов и отправить отдельно?
  • Должен ли я создать таблица ответов с 4 столбцами для разных ответов?

Текущий код:

<?php

$query = ("select questiontable.questionId, questiontable.question, answertable.answerId,answertable.answer, answertable.questionId, questiontable.scoreValue
  FROM questiontable 
  inner join answertable on questiontable.questionId=answertable.questionId   ORDER BY RAND () LIMIT 1 ");
$result =mysqli_query($conn, $query) or die(mysqli_error($conn));

while ($row = mysqli_fetch_assoc($result)){
  $row_cnt = mysqli_num_rows($result);
  echo $row_cnt;    
  echo $row ['question'];
  echo $row ['answer'] ;
  echo $row ['answer'] ;
  echo $row ['answer'];
  echo $row ['answer'];
}
?>

Вот мои таблицы:

CREATE TABLE `braingain`.`questionTable`
 ( `questionId` INT NOT NULL AUTO_INCREMENT , `question` VARCHAR(600) NOT NULL , `scoreValue` INT NOT NULL , `subject` VARCHAR(50) NOT NULL , PRIMARY KEY (`questionId`));

CREATE TABLE `braingain`.`answerTable`
 ( `answerId` INT NOT NULL  , `answer` VARCHAR(600) NOT NULL , 'questionId', isCorrect;

Запрос должен вывести вопросы и 4 связанных ответа в массив.

Желаемый результат

Созданный массив должен выглядеть так:

|         question               | answerA | answerB | answerC | answerD |
| WHICH IS THE CORRECT SPELLING? | APPLE   | APEL    | APPUL   | APPAL   |

Ответы [ 3 ]

1 голос
/ 27 марта 2019

Выполнить два вложенных запроса,

$output = array();
$answer_array = array('answerA','answerB','answerC','answerD');
$query = ("select * from questiontable ORDER BY RAND () LIMIT 1 ");
$result =mysqli_query($conn, $query) or die(mysqli_error($conn));

while ($row = mysqli_fetch_assoc($result)){
    $row_cnt = mysqli_num_rows($result);
    $output['question']=$row['question'];
    $query2 = ("select * from answerTable where questionId = ". $row ['questionId'] order by answerId);
    $result2 =mysqli_query($conn, $query2) or die(mysqli_error($conn));
    $i=0;
    while ($row2 = mysqli_fetch_assoc($result2)){
        $output[answer_array[$i]]=$row2['answer'];
        $i++;
    }
}
print_r($output);
?>
0 голосов
/ 28 марта 2019

хорошо, так что у меня все работает с моим php и т. Д. У меня есть это, повторяя результат, как я хочу, вот код ...

 <?php
    session_start();
    include 'dbconnect.php';

    $output = array();

    $answer_array = array('answerA','answerB','answerC','answerD'); //loads answers into array

    $query = ("select * from questiontable ORDER BY RAND () LIMIT 1 ");//sql query to get questions
    $result =mysqli_query($conn, $query) or die(mysqli_error($conn));

while ($row = mysqli_fetch_assoc($result)){
        $row_cnt = mysqli_num_rows($result);
        $output['question']=$row['question'];
        $query2 = ("select * from answerTable where questionId = '". ($row ['questionId'])."' order by rand()");//sql query to get answers for questions by questionId 
        $result2 =mysqli_query($conn, $query2) or die(mysqli_error($conn));
        $i=0;
        $question=$row ['question'];
        while ($row2 = mysqli_fetch_assoc($result2)){
        $output[$answer_array[$i]]=$row2['answer'];
        $i++;
        $_POST = $output;
        }
                                          }
echo "</br> ";                                    
echo $_POST ['question'];
echo "</br> ";
echo $_POST['answerA'];
echo "</br>";
echo $_POST['answerB'];
echo "</br>";
echo $_POST['answerC'];
echo "</br> ";
echo $_POST['answerD'];
?>

теперь мне нужно сохранить результаты в единстве, чтобы я мог назначить их кнопкам и т. Д. У меня есть, потянув детали, но не знаю, как назначить, например, $_POST['answerA]; для переменной в C #. это мой код C # ...

public class qNaDisplay : MonoBehaviour {
public Text questionDisplayText, answerAText, answerBText, answerCText, answerDText;
public Text questMessage, answerMessage;

private string question, a, b, c, d;


// Use this for initialization
void Start ()
{
    WWW questionURL = new WWW("http://localhost:8080/Project/PHP/questionRequest.php");
    question = questionDisplayText.text;
    a = answerAText.text;
    b = answerBText.text;
    c = answerCText.text;
    d = answerDText.text;
    StartCoroutine(qNaget(questionURL));
}

// Update is called once per frame
void Update () {

}

приватный IEnumerator qNaget (WWW questionURL) {

    yield return  questionURL;
    Debug.Log(questionURL.text);
    if (questionURL.error != null)
    {
        print("There was an error getting the question " + questionURL.error);
    }
    else
    {
         Debug.Log (questionURL.text); // this is a GUIText that will display the scores in game.
    }
}

}

0 голосов
/ 27 марта 2019

Пожалуйста, посмотрите на отступы, что делает код намного более приятным:)

<?php
$query = ("
    SELECT
        questiontable.questionId,
        questiontable.question,
        answertable.answerId,
        answertable.answer,
        answertable.questionId,
        questiontable.scoreValue
    FROM
        questiontable 
    INNER JOIN
        answertable on questiontable.questionId = answertable.questionId
    ORDER BY RAND()
    LIMIT 1
");

$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
$data = [];
$data[] = null;

$keys = [
    'question',
    'answerA',
    'answerB',
    'answerC',
    'answerD',
];

$return = [];
while ($row = mysqli_fetch_assoc($result)){
    if ($data[0] !== $row['question']) {
        $data = [];
        $data[] = $row['question'];
    }

    $data[] = $row['answer'];

    if (count($data) === 5) {
        $dataAssociative = array_combine($keys, $data);
        $return[] = $dataAssociative;
    }
}

var_dump($return);
?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...