如何在PHP代码中从数据库中检索数据

时间:2015-03-07 03:06:37

标签: php mysql

我的代码中有很多错误,但我不知道哪个错误。

我正在尝试从数据库中检索数据并将其粘贴到html中,但是有读取表的问题。数据库有两个表,其中一个是诊断表,另一个是诊断答案。诊断表包含10个问题,每个问题有3个多项选择答案我放在诊断答案表中。我也试着从诊断表中循环问题和答案一样。

<form name="question" action="diagnostic_test_process.php" method="post">`

<fieldset>
<table><?PHP      

$sql=mysql_query("SELECT * FROM diagnostic")
or die ("Problem reading table:". mysql_error());
while ($result = mysql_fetch_array ($sql)){ ?>

<tr>
   <td colspan="2">
   <label for="question"></label>
      <?PHP                                
        echo "<p>".$result["id_diagnostic"].".";
        echo $result["question"]."</p>"; ?>
   </td>
</tr>

 <?php
 $sql=mysql_query
 ("SELECT a.id_answer, a.answer FROM diagnostic_answer a, diagnostic b WHERE a.id_diagnostic = b.id_diagnostic and a.id_diagnostic= " . $result["ïd_diagnostic"])          
 or die ("Problem reading table:". mysql_error());
 while ($value= mysql_fetch_array ($sql)){  ?>

<tr>
   <td>
     <label for="answer"></label>
     <p><input id=<?php echo $answer['id_answer']; ?> type='radio' name='answer' value='1' onClick="calculate()">
     <?php echo $value['answer']; ?></p>
   </td>
</tr>

<?php } 
// close recordset
?>
<?php } ?>

    </table>
</fieldset>

2 个答案:

答案 0 :(得分:1)

错误就在这里。

while ($result = mysql_fetch_array ($sql)){

应该是

while ($result = mysql_fetch_array ($sql, MYSQL_ASSOC)){

while ($result = mysql_fetch_assoc ($sql)){
不要忘记在那里进行第二次循环播放

答案 1 :(得分:0)

我尝试编辑你的一些代码,看看代码并尝试弄明白。你应该去youtube搜索一些教程以供参考。

&#13;
&#13;
<form name="question" action="diagnostic_test_process.php" method="post">`

<fieldset>
<table><?PHP      
mysql_fetch_array ($sql);//This is the issue, don't know what you want

//$result need to be defined here

$sql=mysql_query("SELECT * FROM diagnostic"
while $result = put a defined string here ); 

include the html inside the php loop

echo "<tr>"; //do like this for all below html code
   <td colspan="2">
   <label for="question"></label>
      <?PHP                                
        echo "<p>".$result["id_diagnostic"].".";
        echo $result["question"]."</p>"; ?>
   </td>
</tr>

  
  ?>
  
  
  
 <?php
 $sql=mysql_query
 ("SELECT a.id_answer, a.answer FROM diagnostic_answer a, diagnostic b WHERE a.id_diagnostic = b.id_diagnostic and a.id_diagnostic= " . $result["ïd_diagnostic"])          
 or die ("Problem reading table:". mysql_error());
 while ($value= mysql_fetch_array ($sql)){  ?>

<tr>
   <td>
     <label for="answer"></label>
     <p><input id=<?php echo $answer['id_answer']; ?> type='radio' name='answer' value='1' onClick="calculate()">
     <?php echo $value['answer']; ?></p>
   </td>
</tr>

<?php } 
// close recordset
?>
<?php } ?>

    </table>
</fieldset>
&#13;
&#13;
&#13;