简体   繁体   中英

Delete from database using javascript

I have a page containing a database table with all the rows and columns. What I am trying to do is to select all the rows I want and then delete them when I click on the button.

This is what I've done so far in the table.php page:

<?php 
include "config.php";  //connection to database 
incude "home.js"; 
$funcao="Select * from  palavras";
$result=mysqli_query($link, $funcao);
?>


 <button id="button_apaga" type="button" onclick="delete()" > DELETE </button>      

 <?php  if($result->num_rows > 0)  { ?>

  <table class="table">
      <tr>
          <th>IdPalavra</th>
          <th>Palavra</th>
          <th>Grau de Dificuldade</th>
          <th>Data</th>
          <th>Hora</th>
          <th>Selecionar</th>
      </tr>


    <?php while($row = mysqli_fetch_assoc($result)) { ?>

      <tr role="row">
        <td><?php echo $row['idpalavras']; ?></td>       
        <td><?php echo $row['palavra']; ?></td>
        <td><?php echo $row['graudificuldade']; ?></td>
        <td><?php echo $row['data']; ?></td>
        <td><?php echo $row['hora']; ?></td>
        <td><input type="checkbox" name="check" id="checkbox" /></td>
      </tr>
    <?php } ?>   
      </table> 

    <?php }
    else{
        echo "0 resultados";
    } ?>

JavaScript Page (home.js):

function delete(id){
    var check = document.getElementById('checkbox');
    if(check.checked) {
        // sql query 
    }

My question is how can I do que sql query considering it's in a different page. Can I just open php and put the query inside?

Also how can I receive all the IDs from the selected rows to the function? Thank you in advance.

One approach would be to use AJAX. For the purpose of condensing the code, I'm going to also incorporate jQuery into this solution. I am also going to change your checkbox to an individual button link for the sake of making this a bit less code. A solution to delete multiple at the same time could work similarly to this, but since you're using AJAX most likely this is going to be easier for your users.

Modify table.php

<?php 
include "config.php";  //connection to database 
incude "home.js"; 
$funcao="Select * from  palavras";
$result=mysqli_query($link, $funcao);
?>

 <?php  if($result->num_rows > 0)  { ?>

  <table class="table">
      <tr>
          <th>IdPalavra</th>
          <th>Palavra</th>
          <th>Grau de Dificuldade</th>
          <th>Data</th>
          <th>Hora</th>
          <th>Selecionar</th>
      </tr>


    <?php while($row = mysqli_fetch_assoc($result)) { ?>

      <tr role="row" class="palavras_row">
        <td><?php echo $row['idpalavras']; ?></td>       
        <td><?php echo $row['palavra']; ?></td>
        <td><?php echo $row['graudificuldade']; ?></td>
        <td><?php echo $row['data']; ?></td>
        <td><?php echo $row['hora']; ?></td>
        <td><a href="javascript:void(0);" class="palavras_delete" data-id="<?php echo $row['idpalavras']; ?>">Delete</a></td>
      </tr>
    <?php } ?>   
      </table> 
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js?ver=3.3.1"></script>

<script type="text/javascript">
(function($) {
    $(document).on('click', '.palavras_row a.palavras_delete', function() {
        var _id = $(this).attr('data-id');
        var _row = $(this).parent().parent();
        $.ajax({
            url: 'delete.php',
            data: {
                idpalavras: _id
            },
            type: 'POST',
            dataType: 'json',
            success: function(__resp) {
                if (__resp.success) {
                    _row.remove(); // Deletes the row from the table
                }
            }
        });
    });
})(jQuery);
</script>

Create a new file in the same folder as your table.php and name it delete.php

<?php
$idpalavras = filter_input(INPUT_POST, 'idpalavras', FILTER_SANITIZE_NUMBER_INT);
$success = false;
if ($idpalavras) {
    include "config.php";  //connection to database 
    $funcao="delete from palavras where idpalavras = " . $idpalavras;
    $result=mysqli_query($link, $funcao);
    $success = true;
}
header('Content-Type: application/json');
echo json_encode(array('success' => $success));

The solution above sends a simple command to your PHP backend where the delete query can be run by PHP. You cannot run a mysql command directly from javascript since that is frontend code.

This code is a functional solution, but it is abbreviated; a more complete solution would have more detailed handling of potential errors (either via AJAX or processing your delete query). It should also have some security on your delete.php to make sure unauthorized users aren't able to delete records without the proper permission to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM