PHP实现批量删除(封装)

<!DOCTYPE html> <html> <head> <title>批量删除</title> </head> <body> <script type="text/javascript"> //复选框 function checkall(all) { var ck = document.getElementsByClassName("ck"); if(all.checked) { for(var i=0;i<ck.length;i++) { ck[i].setAttribute("checked","checked"); } } else { for(var i=0;i<ck.length;i++) { ck[i].removeAttribute("checked"); } } } </script> <form action="test.php" method="post"> <table> <tr><th><input type="checkbox"/>id</th><th>名字</th></tr> <!-- 此处调用显示列表函数 --> <?php show() ?> <tr><td colspan="3"><input type="submit" value="批量删除"></td></tr> </table> </form> </body> <?php //显示列表 function show() { //连接数据库 @mysql_connect('localhost','root',''); mysql_select_db('test'); mysql_query('set names utf8'); $sql = "select id,name from test"; $res = mysql_query($sql); //循环取出数据 while($row = mysql_fetch_row($res)) { echo "<tr> <td> <input type='checkbox' value='{$row[0]}' /> {$row[0]} </td> <td>{$row[1]}</td> </tr>"; } } ?> </html>

后台

<?php //接收post传来的数组 $arr = $_POST["item"]; /** * 批量删除 * 思路:把前台批量选择的数据放在数组里,删除该数组即可 * @param $arr <array()> * @return $res 成功or失败 */ function batch_del($arr) { @mysql_connect('localhost','root',''); mysql_select_db('test'); mysql_query('set names utf8'); //把数组元素组合为字符串: $str = implode("','",$arr);   //in 表示多个 $sql = "delete from test where id in('{$str}')"; $res = mysql_query($sql); if (!$res){ echo "删除失败"; }else { if (mysql_affected_rows()>0){ echo "删除成功"; }else { echo "没有行受到影响"; } } } //调用批量删除函数 batch_del($arr);

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/0ca4758c511f33a98a3e10fb0ffc9765.html