search
HomeBackend DevelopmentPHP ProblemHow to delete table contents in batches in php

php method to delete table contents in batches: 1. Create a "list_pl.php" file; 2. Create a "shanchu.php" file to implement the deletion function; 3. Create a modification and update page; 4. Just create the batch deletion page "adminDel.php".

How to delete table contents in batches in php

The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.

How to delete table contents in batches in php?

php operation form data [including batch deletion]

Rendering:

list_pl.php:

<?php

$con = mysqli_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;test&#39;);
mysqli_set_charset($con,&#39;utf8&#39;);
if(!$con){
die(&#39;Could not connect:&#39; . mysql_error($con));
}
$sql = "select * from login";
$result = mysqli_query($con,$sql);
$rows = array();
while($row = mysqli_fetch_assoc($result)){
  $rows[] = $row; 
}  

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
 <html xmlns="http://www.w3.org/1999/xhtml">
  
 <head>  
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
   <title>无标题文档</title>
  <style>
      *{padding:0;margin:0;}
      .pd-lr{padding: 5px 20px}
  </style>
 </head>
 <body>
 <table width="100%" border="1" cellpadding="0" cellspacing="0">  
 <thead>
   <tr>  
     <td width="30">
        全选:<input id="checkAll" type="checkbox">
     </td>
     <td width="30">id</td>
     <td width="30">用户名</td>
     <td width="30">密码</td>
     <td width="30">邮箱</td>
     <td width="40">操作</td>    
     <td width="30">提交时间</td>    
   </tr>
</thead>
<tbody>
   <?php foreach($rows as $k => $v) {
     ?>
		<tr>
		 <td><input type="checkbox" name="box" value="<?= $v[&#39;id&#39;] ?>" class="checkOne"></td>
		 <td><?php echo $v[&#39;id&#39;];?></td>  
		 <td><?php echo $v[&#39;username&#39;];?></td>  
		 <td><?php echo $v[&#39;password&#39;];?></td> 
		 <td><?php echo $v[&#39;email&#39;];?></td>
		 <td>
		   <a href="javascript:confirm_delete(&#39;shanchu.php?sno=<?php echo $v[&#39;id&#39;];?>&#39;)">删除</a>
		   <a href=&#39;xiugai.php?sno=<?php echo $v[&#39;id&#39;];?>&#39;>修改</a> 
		 </td> 
		 <td><?php echo $v[&#39;CreateTime&#39;];?></td>
		</tr>
   <?php } ?>
  </tbody>
 </table>
 <p class="pd-lr">
 <button style="float:left;">批量删除</button>
 <!-- 数据表的总条数 -->
 <p style="float:right;display:inline-block;">总共<span><?php
        $sql2 = "SELECT COUNT(*) FROM login"; //获取某一张表的所有数据
        $all_value = $con->query($sql2);  
			while ($nums=$all_value->fetch_assoc()) {   //输出每一行数据 
			 echo ($nums[&#39;COUNT(*)&#39;]); //获取数据库总条数
            } ?></span>条</p>
 </p> 

 <script src="./jquery-3.2.1.min.js"></script>
 <script>
  //  单项删除
   function confirm_delete(url){
	  if(confirm(&#39;您确定要执行删除操作?&#39;)){
		window.location.href=url;
		}else{
			return false;
			}
	}
   // 全选,反选
$("#checkAll").on(&#39;change&#39;, function () {
    if ($(this).is(":checked")) { // 全选
        $(".checkOne").prop("checked",true);
    } else { // 反选
        $(".checkOne").prop("checked",false);
    }
});
// 批量删除
$(&#39;button&#39;).click(function(){
            var ids=$(&#39;.checkOne:checkbox&#39;);
            var str=&#39;&#39;;
            var count=0;
            for(var i=0;i<ids.length;i++){
                if(ids.eq(i).is(&#39;:checked&#39;)){
                    str+=&#39;,&#39;+ids.eq(i).val();
                    count++;
                }
            }
            var str=str.substr(1);
            if(confirm(&#39;你确定要删除这&#39;+count+&#39;条数据吗?&#39;)){
                //获取id后删除
                $.ajax({
                    type:&#39;GET&#39;,
                    url:&#39;adminDel.php&#39;,
                    // contentType: "application/json;charset=utf-8",
                    data:{&#39;str&#39;:str},
                    // dataType:&#39;json&#39;,//用get方法时不指定这项(可能是json数据不够严谨)
                    success:function(res){
                        if(res>0){
                            for(var i=ids.length-1;i>=0;i--){
                                if(ids.eq(i).is(&#39;:checked&#39;)){
                                    ids.eq(i).parent().parent().remove();
                                }
                            }
                        }
                        alert(&#39;删除成功!&#39;);
                        window.location.reload();
                    },
                    error:function(data){ 
                    console.log("数据加载失败",data); 
                } 
                })
            }
            return false;
        });
   
 </script>
 </body>
 </html>

shanchu.php (You can also directly fill in the path of adminDel.php when deleting a single item):

<?php
 
$aaa = $_GET ["sno"]; //删除方式使用的get,照旧
 
$db = new mysqli("localhost","root","123456","test");
 
$sql = "delete from login WHERE id=&#39;{$aaa}&#39;";
 
if($db->query($sql)){
    //  header("location:list.php");
    echo "<script>alert(&#39;删除成功!&#39;);window.location.href=&#39;list.php&#39;</script>" ;
}else{
    echo "删除失败";
}

?>

xiugai.php (modify page):

<html xmlns="http://www.w3.org/1999/xhtml">
 
<head>
 
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 
  <title>无标题文档</title>
 
</head>
<body>
<h1 id="修改">修改</h1>
 

<?php
 
$sno = $_GET{"sno"};
 
$db = new mysqli("localhost","root","123456","test");
 
$sql = "select * from login WHERE id=&#39;{$sno}&#39;";
 
$r = $db->query($sql);
 
$arr = $r->fetch_row();
 ?>

<form action="update.php" method="post">
<p>id:<input type="text" name="id" value="<?php echo $arr[0]; ?>"/></p>  
<p>用户名:<input type="text" name="username" value="<?php echo $arr[1]; ?>"/></p>  
<p>密码:<input type="text" name="password" value="<?php echo $arr[2]; ?>"/></p>  
<p>邮箱:<input type="text" name="email" value="<?php echo $arr[4]; ?>"/></p> 
</p>
  <p><input type="submit" value="修改完毕"/></p>
</form>

</body>
 
</html>

xiugai.php The update page can also be written like this:

<?php
 
//创建连接:四个参数分别为 服务器地址、用户名、密码、数据库名
$conn = mysqli_connect("localhost","root","123456","test");
$sno = $_GET{"sno"}; 
//查询数据的sql语句
$sql = "select * from login WHERE id=&#39;{$sno}&#39;";
 
//执行语句接收返回值
$result = mysqli_query($conn,$sql);
//输错查询的数据
while ($row = mysqli_fetch_array($result)){?>
<style type="text/css">
	.list{margin: 0 auto;}
	.list p{font-size: 1rem;padding: 5px 0;}
	.list p span{display: inline-block;width: 100px;}
	.list p input{padding: 5px 0;outline:none;border: 1px solid #ccc;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;}
	.list p input:focus {border-color: #66afe9;outline: 0;-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);}
	.list .up_btn input{padding: 5px 10px;font-size: 1rem;border: 1px solid #2285ed;background-color: #FFF;}
	.list .up_btn input:hover{background-color: #2285ed;color: #fff;}
	.tran-b{-webkit-transition: all ease-out .5s;-o-transition: all ease-out .5s;transition: all ease-out .5s;}
</style>
<form action="./update.php" method="post" class="list">
	<p><span style="color: #2285ed;">id:<input type="hidden" value="<?php echo $row[&#39;id&#39;];?>" name="id" /><?php echo $row[&#39;id&#39;];?></span></p>
	<p><span>用户名:</span><input type="text" name="username" value="<?php echo $row[&#39;username&#39;];?>" /></p>
	<p><span>密码:</span><input type="text" name="password" value="<?php echo $row[&#39;password&#39;];?>" /></p>
	<p><span>邮箱:</span><input type="text" name="email" value="<?php echo $row[&#39;email&#39;];?>" /></p>
	</p>
	<p class="up_btn"><input type="submit" value="修改完毕" class="tran-b"/></p>
</form>
<?php }?>

update.php (update Page):

<?php
error_reporting(E_ALL ^ E_NOTICE);
$id = $_POST["id"];
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
 
$db = new mysqli("localhost","root","123456","test");
 
$sql = "update login set username=&#39;{$username}&#39;,password=&#39;{$password}&#39;,email=&#39;{$email}&#39; WHERE id=&#39;{$id}&#39;";

if($db->query($sql)){
    //  header("location:list.php");
    echo "<script>alert(&#39;修改成功!&#39;);window.location.href=&#39;list_pl.php&#39;</script>" ;
}else{
    echo "修改失败";
}     

?>

adminDel.php (batch delete page):

<?php  
error_reporting(E_ALL ^ E_NOTICE); 
    // header(&#39;content-type:text/html;charset=utf-8&#39;);
    // header(&#39;Content-type: application/json;charset=utf-8&#39;);
    $str=$_GET[&#39;str&#39;];
    // echo $str;
    $link = mysqli_connect( &#39;localhost&#39; , &#39;root&#39; , &#39;123456&#39; , &#39;test&#39; );
    // mysqli_query($link,&#39;set names utf8&#39;);   
    $sql=&#39;delete from login where id in (&#39;.$str.&#39;)&#39;;
    mysqli_query($link,$sql);
?>

Problems encountered:

ajax reports an error when submitting data. I am running it locally. Reference: https://ask.csdn.net/questions/325174dataType:'json' ,Change to dataType:'text', and it will work, or delete dataType:'json'.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to delete table contents in batches in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!