2014-10-27 94 views
0

有一個id問題和choiecs數據庫和一個答案(多選)我想顯示它的所有數據庫中的左邊有一個複選框。最後我會提交一個提交按鈕,並且我想要在表格下顯示所有問題。我的嘗試。必須有一個更簡單的方法。謝謝!如何從數據庫中選擇行並用複選框顯示它們?

$result = mysqli_query($con,"SELECT id,question,choiceA,choiceB,choiceC,choiceD,answer FROM q_and_a "); 

echo "<table border='1'> 
<tr> 
<th>Add</th> 
<th>#</th> 
<th>Question</th> 
<th>A</th> 
<th>B</th> 
<th>C</th> 
<th>D</th> 
<th>Answer</th> 
</tr>"; 

echo '<form method="POST" action="makeTest.php">'; 

while($row = mysqli_fetch_array($result)) 
{ 

echo "<tr>"; 
echo '<td><input type="checkbox" name="questions[]" value="yes"></td>'; 
echo "<td>" . $row['id'] . "</td>"; 
echo "<td>" . $row['question'] . "</td>"; 
echo "<td>" . $row['choiceA'] . "</td>"; 
echo "<td>" . $row['choiceB'] . "</td>"; 
echo "<td>" . $row['choiceC'] . "</td>"; 
echo "<td>" . $row['choiceD'] . "</td>"; 
echo "<td>" . $row['answer'] . "</td>"; 
echo "</tr>"; 
} 
echo "</table>"; 

?> 


+0

請問涉及的jQuery intrest你的解決方案? – jiy 2014-10-27 16:51:57

回答

0

我建議你扔的jQuery混進去。

保持HTML代碼不在您的PHP代碼中,只是用它來查詢數據庫。

然後使用AJAX/JSON更新DOM。

更新 - 這已經過測試(驗證工作),並且一些錯誤已經修復。

ajax.php:

<?php 

    $action = $_POST["action"]; 

    if ($action == "getQuestions") { 
     echo getQuestions(); 
    } 

    function getQuestions() { 
     try { 
      $db = new PDO("mysql:host=localhost;charset=utf8", "root", "root"); 
      $cmd = $db->prepare(" 
       SELECT id, question , choiceA ,choiceB ,choiceC ,choiceD , answer 
       FROM pl2.questions; 
      "); 
      $cmd->execute(); 
      $rows = array(); 
      while($r = $cmd->fetch(PDO::FETCH_ASSOC)) { $rows[] = $r; } 
      $json = json_encode($rows); 
      return($json); 
     } catch (PDOException $e) { echo $e->getMessage(); return; } 
    } 

?> 

questions.html

<html> 
<head> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
    <script language="javascript"> 

     var questionsJson = ''; 

     $(document).ready(function() { 
      getQuestions(); 
     }); 

     function getQuestions() { 
      $.post('ajax.php', { action: 'getQuestions' }, function(data) { 
       questionsJson = data; 
       displayQuestions(); 
      },'json'); 
     } 

     function displayQuestions() { 
      var colAry = ['id', 'question', 'choiceA', 'choiceB', 'choiceC', 'choiceD', 'answer']; 
      for (var i = 0; i < questionsJson.length; i++) { 
       var q = questionsJson[i]; 
       var row = '<tr><td><input type="checkbox" name="questions[]" value="yes"></td>'; 
       for (var j = 0; j < colAry.length; j++) { 
        row += '<td>' + q[colAry[j]] + '</td>'; 
       } 
       $('#mainTable').append(row + '</tr>'); 
      } 
     } 

    </script> 
</head> 
<body> 
    <table id="mainTable" border="1"> 
     <tr> 
      <th>Add</th> 
      <th>#</th> 
      <th>Question</th> 
      <th>A</th> 
      <th>B</th> 
      <th>C</th> 
      <th>D</th> 
      <th>Answer</th> 
     </tr> 
    </table> 
</body> 
</html> 
相關問題