php大量刪除資料程式碼

來源:互聯網
上載者:User

我們刪除需要的sql文法

delete from aaaa where id in(1,2,3)這裡面的1,2,3就是我們需要刪除的記錄了

那麼在php中如何來做

1、首先在文章列表頁面(list.php),將多選筐命名為:“$del_id[]”,值為文章ID號。
 例如(list.php):

 代碼如下 複製代碼

<form name="del_form" action="del.php" method="post">
<?php
$result=mysql_query("select * from news");
while($rs=mysql_fetch_array($result)){
 ?>
<input name="del_id[]" type="checkbox" id="del_id[]" value="<?=$rs[id]?>" /><?=$rs[title]?>
 <?php
}
 ?>
 </form>

2、處理頁面(del.php):

<?php
 if($del_id!=""){
 $del_num=count($del_id);
 for($i=0;$i<$del_num;$i++){
 mysql_query("Delete from news where id='$del_id[$i]'");
 }
 echo("<script type='text/javascript'>alert('刪除成功!');history.back();</script>");
}else{
 echo("<script type='text/javascript'>alert('請先選擇項目!');history.back();</script>");
}
?>

案例分析:

上面批量核心代碼是 表單名為del_id[]與

 代碼如下 複製代碼

for($i=0;$i<$del_num;$i++){
 mysql_query("Delete from news where id='$del_id[$i]'");
}

這個就是擷取提交過來的數組然後我們再遍曆一條條刪除了這個與我們最前面的說法更小一樣,其實我們可以加地改進

 代碼如下 複製代碼

$ids = implode(',',$_POST['del_id']);
$sql ="delete from aaaa where id in($ids)";
mysql_query($Sql);


這樣就可以簡少很多的語句哦,當然上面需要判斷提交過來的是不是數組了,最後我們對del.php檔案進行代碼最佳化刪除操作

 代碼如下 複製代碼

<?php
 if(is_array($del_id)){
 
$ids = implode(',',$_POST['del_id']);
$sql ="delete from aaaa where id in($ids)";
 if( mysql_query($Sql))
{
echo '刪除成功';
}
else
{
echo '刪除失敗';
}
}

 
}
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.