Example of implementing batch data deletion function by PHP+JS

  • 2021-08-16 23:20:19
  • OfStack

In this paper, an example is given to describe the function of batch deletion of data by PHP+JS. Share it for your reference, as follows:

Form


<form id="form2" name="form2" method="post" action="del_product.php" onsubmit="return checkF(this)">
<label>
<input type="checkbox" name="id[]" value="<?php echo $rs['id'];?>" style="background:none; border:none;" />
</label>
<div style="padding-left:20px;"><input type="button" value=" All selection " style="background:url(images/cheall.jpg) no-repeat; width:60px; height:23px; border:none;" onClick="selectBox('all')"/>
<input type="button" value=" Reverse selection " style="background:url(images/cheall.jpg) no-repeat; width:60px; height:23px; border:none;" onClick="selectBox('reverse')"/>
<input type="submit" name="btnSave" style="background:url(images/cheall.jpg) no-repeat; width:60px; height:23px; border:none;" value=" Delete "/></div>
</form>

JS


<script type="text/javascript" language="javascript">
    function selectBox(selectType){
    var checkboxis = document.getElementsByName("id[]");
    if(selectType == "reverse"){
      for (var i=0; i<checkboxis.length; i++){
        //alert(checkboxis[i].checked);
        checkboxis[i].checked = !checkboxis[i].checked;
      }
    }
    else if(selectType == "all")
    {
      for (var i=0; i<checkboxis.length; i++){
        //alert(checkboxis[i].checked);
        checkboxis[i].checked = true;
      }
    }
   }
</script>

del_product.php


<?php
include('checkadmin.php');
header('Content-Type: text/html; charset=utf-8');
if($_POST['btnSave']){
 if(empty($_POST['id'])){
    echo"<script>alert(' You must select 1 Product , You can delete it !');history.back(-1);</script>";
    exit;
  }else{
/* If you want to get all the values, use the following code */
   $id= implode(",",$_POST['id']);
   $str="DELETE FROM `product` where id in ($id)";
   mysql_query($str);
  echo "<script>alert(' Delete successful! ');window.location.href='product_list.php';</script>";
}
}
?>

Attachment: Database operation class implemented by php

Db. php:


<?php
Class DB {
  private $link_id;
  private $handle;
  private $is_log;
  private $time;
  // Constructor 
  public function __construct() {
    $this->time = $this->microtime_float();
    require_once("config.db.php");
    $this->connect($db_config["hostname"], $db_config["username"], $db_config["password"], $db_config["database"], $db_config["pconnect"]);
    $this->is_log = $db_config["log"];
    if($this->is_log){
      $handle = fopen($db_config["logfilepath"]."dblog.txt", "a+");
      $this->handle=$handle;
    }
  }
  // Database connection 
  public function connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect = 0,$charset='utf8') {
    if( $pconnect==0 ) {
      $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true);
      if(!$this->link_id){
        $this->halt(" Database connection failed ");
      }
    } else {
      $this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw);
      if(!$this->link_id){
        $this->halt(" Database persistent connection failed ");
      }
    }
    if(!@mysql_select_db($dbname,$this->link_id)) {
      $this->halt(' Database selection failed ');
    }
    @mysql_query("set names ".$charset);
  }
  // Query 
  public function query($sql) {
    $this->write_log(" Query  ".$sql);
    $query = mysql_query($sql,$this->link_id);
    if(!$query) $this->halt('Query Error: ' . $sql);
    return $query;
  }
  // Get 1 Records ( MYSQL_ASSOC , MYSQL_NUM , MYSQL_BOTH ) 
  public function get_one($sql,$result_type = MYSQL_ASSOC) {
    $query = $this->query($sql);
    $rt =& mysql_fetch_array($query,$result_type);
    $this->write_log(" Get 1 A record  ".$sql);
    return $rt;
  }
  // Get all records 
  public function get_all($sql,$result_type = MYSQL_ASSOC) {
    $query = $this->query($sql);
    $i = 0;
    $rt = array();
    while($row =& mysql_fetch_array($query,$result_type)) {
      $rt[$i]=$row;
      $i++;
    }
    $this->write_log(" Get all records  ".$sql);
    return $rt;
  }
  // Insert 
  public function insert($table,$dataArray) {
    $field = "";
    $value = "";
    if( !is_array($dataArray) || count($dataArray)<=0) {
      $this->halt(' No data to insert ');
      return false;
    }
    while(list($key,$val)=each($dataArray)) {
      $field .="$key,";
      $value .="'$val',";
    }
    $field = substr( $field,0,-1);
    $value = substr( $value,0,-1);
    $sql = "insert into $table($field) values($value)";
    $this->write_log(" Insert  ".$sql);
    if(!$this->query($sql)) return false;
    return true;
  }
  // Update 
  public function update( $table,$dataArray,$condition="") {
    if( !is_array($dataArray) || count($dataArray)<=0) {
      $this->halt(' No data to update ');
      return false;
    }
    $value = "";
    while( list($key,$val) = each($dataArray))
    $value .= "$key = '$val',";
    $value .= substr( $value,0,-1);
    $sql = "update $table set $value where 1=1 and $condition";
    $this->write_log(" Update  ".$sql);
    if(!$this->query($sql)) return false;
    return true;
  }
  // Delete 
  public function delete( $table,$condition="") {
    if( empty($condition) ) {
      $this->halt(' There are no conditions set for deletion ');
      return false;
    }
    $sql = "delete from $table where 1=1 and $condition";
    $this->write_log(" Delete  ".$sql);
    if(!$this->query($sql)) return false;
    return true;
  }
  // Returns a result set 
  public function fetch_array($query, $result_type = MYSQL_ASSOC){
    $this->write_log(" Returns a result set ");
    return mysql_fetch_array($query, $result_type);
  }
  // Get the number of records 
  public function num_rows($results) {
    if(!is_bool($results)) {
      $num = mysql_num_rows($results);
      $this->write_log(" The number of records obtained is ".$num);
      return $num;
    } else {
      return 0;
    }
  }
  // Release the result set 
  public function free_result() {
    $void = func_get_args();
    foreach($void as $query) {
      if(is_resource($query) && get_resource_type($query) === 'mysql result') {
        return mysql_free_result($query);
      }
    }
    $this->write_log(" Release the result set ");
  }
  // Gets the last inserted id
  public function insert_id() {
    $id = mysql_insert_id($this->link_id);
    $this->write_log(" Last inserted id For ".$id);
    return $id;
  }
  // Close the database connection 
  protected function close() {
    $this->write_log(" Database connection closed ");
    return @mysql_close($this->link_id);
  }
  // Error prompt 
  private function halt($msg='') {
    $msg .= "\r\n".mysql_error();
    $this->write_log($msg);
    die($msg);
  }
  // Destructor 
  public function __destruct() {
    $this->free_result();
    $use_time = ($this-> microtime_float())-($this->time);
    $this->write_log(" Complete the entire query task , The time taken is ".$use_time);
    if($this->is_log){
      fclose($this->handle);
    }
  }
  // Write to log file 
  public function write_log($msg=''){
    if($this->is_log){
      $text = date("Y-m-d H:i:s")." ".$msg."\r\n";
      fwrite($this->handle,$text);
    }
  }
  // Get the number of milliseconds 
  public function microtime_float() {
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
  }
}
?>

config.db.php


<?php
  $db_config["hostname"] = "localhost"; // Server address 
  $db_config["username"] = "root"; // Database user name 
  $db_config["password"] = "123"; // Database password 
  $db_config["database"] = "test"; // Database name 
  $db_config["charset"] = "utf8";// Database coding 
  $db_config["pconnect"] = 1;// Open a persistent connection 
  $db_config["log"] = 1;// Open log 
  $db_config["logfilepath"] = './';// Open log 
?>

For more readers interested in PHP related contents, please check the topics on this site: "Introduction to php+mysql Database Operation", "Summary of php+mysqli Database Programming Skills", "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: