PHP for循环不显示正确的数据

时间:2013-08-31 14:37:55

标签: php mysql

我有这个PHP代码/表单:

<form method="post" action="tickets_report2.php">
<table width="800" border="0" cellspacing="5" cellpadding="5">
  <tr>
    <td><strong>Select</strong></td>
    <td><strong>Company</strong></td>
  </tr>
  <?php
  $sql="SELECT * from customer ";
  $rs=mysql_query($sql,$conn) or die(mysql_error());
  $counter=0;
  while($result=mysql_fetch_array($rs)) {
    $counter++;
    echo '<tr>
       <td><input type="checkbox" value="'.$result["sequence"].'" name="checkbox'.$counter.'" /></td>
       <td>'.$result["company"].'</td>
    </tr>';
  }
  echo '<input type="hidden" name="counter" value="'.$counter.'" />';
  ?>
  </table>
  <input type="submit" name="submit" value="Next" />
</form>

并在表单操作页面上:

<table width="800" border="0" cellspacing="5" cellpadding="5">
  <tr>
    <td><strong>Company</strong></td>
  </tr>
  <?php
  for($i=1; $i<=$_POST["counter"]; $i++) {
    if($_POST["checkbox$i"]) {
      $sql="SELECT * from customer where sequence = '".$i."' ";
      $rs=mysql_query($sql,$conn) or die(mysql_error());
      $result=mysql_fetch_array($rs);       
      echo '<tr>
                    <td>'.$result["company"].'</td>
      </tr>';
    }
  }
  ?>
</table>

让我说我检查数据库中行的表单上的复选框,序列为278,SQL查询应该说SELECT * from customer where sequence = '278'但显示SELECT * from customer where sequence = '1'

我认为它使用的是计数器而不是客户序列

我需要更改什么才能使其正常工作,以便选择正确的客户

2 个答案:

答案 0 :(得分:1)

在表单操作页面上,它应显示为:

if($_POST["checkbox$i"]) {
    $sql="SELECT * from customer where sequence = '".$_POST["checkbox$i"]."' ";

注意:清理您的输入。

答案 1 :(得分:0)

表单页面:

<form method="post" action="tickets_report2.php">
<table width="800" border="0" cellspacing="5" cellpadding="5">
  <tr>
    <td><strong>Select</strong></td>
    <td><strong>Company</strong></td>
  </tr>
<?php
$sql="SELECT * from customer ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$counter=0;
while($result=mysql_fetch_array($rs))
{
    $counter++;
    echo '<tr>
         <td><input type="checkbox" value="'.$result["sequence"].'" name="checkbox['.$counter.']" /></td>
         <td>'.$result["company"].'</td>
         </tr>';
}
?>
</table>
<input type="submit" name="submit" value="Next" />
</form>

行动页面:

<table width="800" border="0" cellspacing="5" cellpadding="5">
  <tr>
    <td><strong>Company</strong></td>
  </tr>
<?php
foreach($_POST["checkbox"] as $value)
{
        $sql="SELECT * from customer where sequence = '".$value."' ";
        $rs=mysql_query($sql,$conn) or die(mysql_error());
        $result=mysql_fetch_array($rs);     
        echo '<tr>
                    <td>'.$result["company"].'</td>
                  </tr>';
}
?>
</table>