Monday, March 27, 2017

How to delete multiple mysql table rows with checkbox in php pdo

index.php file
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.   <head>
  4.     <meta charset="utf-8">
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">
  7.     <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
  8.     <title>Bootstrap 101 Template</title>
  9.    <!-- Latest compiled and minified CSS -->
  10. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  11.     
  12.   </head>
  13.   <body>
  14.    
  15.     <div class="container">
  16.     <div class="col-md-6">
  17.      <h1>multi delete</h1>
  18.     <form method="post" action="delete.php">
  19.   <?php
  20. require_once 'db.php';
  21. $stmt = $db_con->prepare("select * from multi");
  22. $stmt->execute();
  23. while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
  24.   ?>
  25.   <input type="checkbox" name="delete23[]" value="<?php echo $row['id']; ?>">
  26.   <?php echo $row['id']; ?>
  27. <?php echo $row['multi']; ?><hr>
  28. <?php
  29. }
  30.   ?>
  31.   <input type="submit" name="delete" class="btn-warning" value="submit">
  32.     </form>
  33.     </div>
  34.     </div>
  35.   </body>
  36. </html>
db.php file
  1. <?php
  2. $db_host = "localhost";
  3.     $db_name = "hey";
  4.     $db_user = "root";
  5.     $db_pass = "";
  6.     
  7.     try{
  8.         
  9.         $db_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
  10.         $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  11.     }
  12.     catch(PDOException $e){
  13.         echo $e->getMessage();
  14.     }
  15. ?>
delete.php file
  1. <?php
  2.   require_once 'db.php';
  3. if($_POST['delete'])
  4. {
  5. $delete= implode(",", $_POST['delete23']);
  6.  if($delete=='')
  7.   {
  8. echo "<script>alert('Nothing Selected to Delete!!!'); window.location='index.php'</script>";
  9.   }
  10. $sql = "Delete from multi where id IN ($delete)";
  11. // use exec() because no results are returned
  12. $db_con->exec($sql);
  13. echo "<script>alert('Successfully Delete!!!'); window.location='index.php'</script>";
  14. }
  15. ?>

VIDEO TUTORIAL



No comments:

Post a Comment