使用复选框从mysql中删除多行

时间:2014-03-14 11:58:49

标签: php mysql sql

我需要使用复选框从mysql中删除多行。有人可以帮我识别我的代码中的错误

 <?php

    $host="localhost"; // Host name 
    $username="xxxx"; // Mysql username 
    $password="xxxx"; // Mysql password 
    $db_name="xxxx"; // Database name 
    $tbl_name="xxx"; // Table name


    // Connect to server and select database. 
    mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
    mysql_select_db("$db_name")or die("cannot select DB"); 
    // Retrieve data from database 
    $sql="SELECT * FROM $tbl_name ORDER BY id ASC";
    $result=mysql_query($sql); 
    // num rows
    $count=mysql_num_rows($result);
    // Start looping rows in mysql database. 
    while($rows=mysql_fetch_array($result)){ 
    ?> 


    <table id="rows" width="100%" border="1" bordercolor="#000" cellspacing="1"       cellpadding="3" cellwidth="100" float="left" margin-left="20px" >
    <tr>
    <td width="2%" align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox"   id="checkbox[]" value="<? echo $rows['id']; ?>"></td>
    <td width="1%" BGCOLOR="#fff"><? echo $rows['id']; ?></td>
    <td width="22%" BGCOLOR="#fff"><? echo $rows['location']; ?></td>
    <td width="22%" BGCOLOR="#fff"><? echo $rows['type']; ?></td> 
    <td width="22%" BGCOLOR="#fff"><? echo $rows['qnty']; ?></td> 
    <td width="22%" BGCOLOR="#fff"><? echo $rows['enteredby']; ?></td>
    </tr>
    <?php
    }
    ?>

    <tr>
    <td colspan="5" align="left" bgcolor="#FFFFFF"><input name="delete" type="submit"  id="delete" value="Delete Row"></td>
    </tr>

    <?php

    // Check if delete button active, start this 
    if($delete){
    for($i=0;$i<$count;$i++){
    $del_id = $checkbox[$i];
    $sql = "DELETE FROM $tbl_name WHERE id='$del_id'";
    $result = mysql_query($sql);
    }
    // if successful redirect to delete_multiple.php 
    if($result){
    echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete_multiple.php\">";
    }
    }
    mysql_close();
    ?>

    </table>

1 个答案:

答案 0 :(得分:2)

尝试

if(!empty($checkbox)) {
   $sql = "DELETE FROM $tbl_name WHERE id IN(".implode(",", $checkbox).")";
   $result = mysql_query($sql);
}