2016-12-10 8 views
0

私はphpを初めて使い、テストとしてデータベースに保存された質問を読み込んで、回答を選択するための入力ラジオボタン付きのテーブルに表示するアプリケーションを作成しました。 4つのテーブルがあります。質問、回答、ユーザー、userexam。各テーブルの行には、インデックスとしてのIDが含まれています。私が問題を抱えているのは、送信ボタンがクリックされたときに値をデータベースに代入することです。私はどのようにループし、個々のidを個別に定義することなく、各質問の値をデータベースに追加しますか?データベースへのフィールド値の追加

+0

これは間違いありませんか? $ sql = "INSERT INTO $ userexam(answerID、questionID、userID)VALUES( '$ answer'、 '$ question'、 '$ student')"; –

答えて

0

mysqlのすべての場所でmysqli(mysql-improved)を使用してください。

<?php 
//Set database conection 
$conection=mysqli_connect('localhost','root','','Your database name'); 
// Check connection 
if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

$getQuestions = " 
    SELECT 
     * 

    FROM 
     questions 
    WHERE questions.active = '1' 

    ORDER BY 
     questionID 
"; 
$qResult = mysqli_query($conection,$getQuestions); 

$tableString = "<table> 
        <tr> 
         <th> 
          Questions 
         </th> 
         <th> 
          Answers 
         </th> 
        </tr>"; 

while ($qRow = mysqli_fetch_assoc($qResult)) { 
    $getAnswers = " 
     SELECT 
      * 
     FROM 
      answers a 
     WHERE 
      a.questionID = '" . $qRow['questionID'] . "' 
     ORDER BY 
      a.questionID, 
      a.answerNumber 
    "; 
    $aResult = mysqli_query($conection,$getAnswers); 

    $tableString .= "<tr> 
         <td>" . 
          $qRow['question'] . 
         "</td> 
         <td>"; 

    while ($aRow = mysqli_fetch_assoc($aResult)) { 
     if ($aRow['correct'] == 1) { 
      $tableString .= "<input name=". $qRow['questionID'] ." 
           type='radio' 
          >" . 
           $aRow['answerValue'] . "<br />"; 
     } else { 

      $tableString .= "<input name=". $qRow['questionID'] ." 
           type='radio' 
          >" . 
           $aRow['answerValue'] . "<br />"; 
     } 
     $answer=$_POST['. $aRow["answerID"] .']; 
     $question=$_POST['. $qRow["questionID"] .']; 
     $student=$_POST['userID']; 

     // Insert data into mysql 
     $sql="INSERT INTO userexam(answerID, questionID, userID)VALUES('$answer', '$question', '$student')"; 
     $result=mysqli_query($conection,$sql); 
    } 


} 
$tableString .= "</table>"; 
echo $tableString; 
mysqli_close($conection); 
?> 
関連する問題