2013-08-31 27 views
0

我有這樣的PHP代碼/形式:PHP for循環顯示不正確的數據

<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'

我認爲它使用計數器而不是客戶序列

什麼我需要改變,以得到這個工作正常,因此選擇正確的客戶(S)

+0

只是一個小問題丟回:爲什麼你認爲代碼應該顯示在所有這些數據呢? – hakre

+0

你可以從表單操作頁面發佈print_r($ _ REQUEST)的結果嗎? – DrewP84

+0

這可能是您的解決方案: 通過這樣做將每個複選框添加到數組:

回答

1

在表單動作頁應改爲:

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

注:淨化你的投入。

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>