2014-10-27 132 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> 
相关问题