简体   繁体   English

如何使用AJAX从MySQL表中删除记录?

[英]How to delete Record from MySQL Table with AJAX?

I want to do a button with an image X and when you click the button, it removes a row in the database, only at this moment. 我想用图像X做一个按钮,当您单击按钮时,仅在此刻它才删除数据库中的一行。

teste-checkbox.php teste-checkbox.php

<style>
table {
  font-family: verdana;
  font-size: 12px;
}

table th {
  text-align: left;
  background: #D3D3D3;
  padding: 2px;
}

table tr:hover {
  background: #EFEFEF;
}

table tr {
  text-align: left;
}

table td {
  padding: 5px;
}

table td a {
  color: #0454B5;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<body>
<!--

    T A B E L A  «» C O M E Ç A

!-->
<?php
error_reporting(0);
$servername = "localhost";
$username = "PAP_Login";
$password = "pap123";
$dbname = "PAP_Login";
$datatable = "registo_anomalias"; // MySQL table name
$results_per_pagina = 5; // number of results per pagina

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
?>
<div class="um-bocado-para-cima">
<?php
if (isset($_GET["pagina"])) { $pagina  = $_GET["pagina"]; } else { $pagina=1; };
$start_from = ($pagina-1) * $results_per_pagina;
$sql = "SELECT * FROM ".$datatable." ORDER BY deleted ASC LIMIT $start_from, ".$results_per_pagina;
$rs_result = $conn->query($sql);
?>
  <table width="40%" border="0" class="hover">
<tr>
    <th bgcolor="#CCCCCC"><strong>ID</strong></th>
    <th bgcolor="#CCCCCC"><strong>Tipo de Sala</strong></th>
    <th bgcolor="#CCCCCC"><strong>Tipo de Avaria</strong></th>
    <th bgcolor="#CCCCCC"><strong>Data de Submissão</strong></th>
    <th bgcolor="#CCCCCC"><strong>Hora de Submissão</strong></th>
    <th bgcolor="#CCCCCC"><strong>Estado</strong></th>
    <th bgcolor="#CCCCCC"><strong>Editar</strong></th>
</tr>
<?php 
 while($row = $rs_result->fetch_assoc()) {
?> 
<?php
$tipo_de_sala = array(
'I' => 'Informática',
'N' => 'Normal',
'O' => 'Outro'
);

$deleted = array(
'0' => 'Não arranjado',
'1' => 'Arranjado'
);
?>
<tr id="<?php echo $row['id_avaria']; ?>" >
    <td>
      <a href="AvariaDocumento.php?id=<?php echo $row['id_avaria']; ?>"><?php echo $row['id_avaria']; ?></a>
    </td>
    <td><? echo strtr($row["tipo_sala"], $tipo_de_sala); ?></td>
    <td><? echo $row["tipo_avaria"]; ?></td>
    <td><? echo $row["data_subm"]; ?></td>
    <td><? echo $row["hora_subm"]; ?></td>
    <td>
      <!-- consultar em https://pt.stackoverflow.com/questions/5675/como-verificar-se-um-checkbox-est%C3%A1-checado-com-php -->
      <? echo strtr($row["deleted"], $deleted); ?>
    </td>
    <td></td>
<!--
    <td>
      <a href="EdicaoAvaria.php?id=<?php echo $row['id_avaria']; ?>"><img src="img/lapis.png"></a>
    </td>
-->
</tr>
<?php 
}; 
?> 
  </table>
 </div>

<div class="pagination um-bocado-para-cima">
<?php 
$sql = "SELECT COUNT(id_avaria) AS total FROM ".$datatable;
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$total_paginas = ceil($row["total"] / $results_per_pagina); // calculate total paginas with results

if($row['total'] > 5){
    for ($i=1; $i<=$total_paginas; $i++) {  // print links for all paginas
        echo "<a href='Administrador.php?pagina=".$i."'";
        if ($i==$pagina)  echo " class='curpage'";
        echo ">".$i."</a> ";
    }
}
?>
</div>
<?php
$id = $row['id_avaria'];
?>
<!--

    T A B E L A  «» T E R M I N A

!-->
</body>
<script>
$(document).ready(function() {
  // show buttons on tr mouseover
  $(".hover tr").live("mouseenter", function() {
    $(this).find("td:last-child").html('<a href="javascript:void(0);" onClick="editrow(' + $(this).attr("id") + ')"><img src="img/lapis.png"></a>&nbsp;&nbsp;<a href="javascript:void(0);" onClick="deleterow(' + $(this).attr("id") + ') <span class="delete" id="del_<?php echo $row['id_avaria']; ?>"><img src="img/remover.png"></span></a>');
  }); //

  // remove button on tr mouseleave
  $(".hover tr").live("mouseleave", function() {
    $(this).find("td:last-child").html("&nbsp;");
  });

  // TD click event
  $(".hover tr").live("click", function(event) {
    if (event.target.nodeName == "TD") {
      alert("You can track TD click event too....Isnt it amazing !!!");
    }
  });
});
editrow = function(itemId) {
  alert("You clicked 'Edit' link with row id :" + itemId);
}
deleterow = function(itemId) {

}
</script>
<script>
$(document).ready(function(){

 // Delete 
 $('.delete').click(function(){
  var el = this;
  var id = this.id;
  var splitid = id.split("_");

  // Delete id
  var deleteid = splitid[1];

  // AJAX Request
  $.ajax({
   url: 'remover-dados.php',
   type: 'POST',
   data: { id:deleteid },
   success: function(response){

    // Removing row from HTML Table
    $(el).closest('tr').css('background','tomato');
    $(el).closest('tr').fadeOut(800, function(){ 
     $(this).remove();
    });

   }
  });

 });

});
</script>
<!--
http://makitweb.com/how-to-delete-record-from-mysql-table-with-ajax/
-->

remover-dados.php remover-dados.php

<?php
error_reporting(0);
$servername = "localhost";
$username = "PAP_Login";
$password = "pap123";
$dbname = "PAP_Login";
$datatable = "registo_anomalias"; // MySQL table name

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
?>
<?php 

$id = $_POST['id_avaria'];

// Delete record
$query = "DELETE FROM ".$datatable." WHERE id_avaria=".$id;
mysqli_query($con,$query);

echo 1;

What am I doing wrong? 我究竟做错了什么?

Your problem is that you send the ID via GET method and you want to retrieve it with POST. 您的问题是您通过GET方法发送了ID,并且想通过POST检索它。

instead of using 而不是使用

$id = $_POST['id_avaria'];

use 采用

$id = intval($_POST['id_avaria']);

also add class delete to a tag element 还可以将class delete添加到tag元素

remove this function because you don't use it at all 删除此功能,因为您根本不使用它

deleterow = function(itemId) {

}

change code with invoking delete to: 通过调用删除将代码更改为:

<a class="delete"><span class="delete" data_id="<?php echo $row['id_avaria']; ?>"><img src="img/remover.png"></span></a>

the last thing is to preventDefault behaviour of click and add geting data-id attribute 最后一件事是防止click的默认行为并添加geting data-id属性

$('.delete').click(function(e){
  e.preventDefault();
  var deleteid = $(this).attr('data-id');

and it would be nice also to check if this variable is passed, for example via isset() function + using prepared statements 并且最好检查是否通过了此变量,例如通过isset()函数+使用准备好的语句

full code: 完整代码:

$id = intval($_GET['id_avaria']);

if (!empty($_GET['id_avaria']) {
   $id = intval($_GET['id_avaria']);

   $stmt = $mysqli->prepare("DELETE FROM ".$datatable." WHERE id_avaria=?");

   $stmt->bind_param($stmt, "d", $id);
   $stmt->execute($stmt);

   if ($stmt->affected_rows($stmt) > 0) {
      echo 'deleted';
   } else {
      echo 'failed to delete';
   }

   $stmt->close();
}

$conn->close();

In your AJAX call you call the parameter id 在您的AJAX调用中,您调用参数id

  // Delete id
  var deleteid = splitid[1];

  // AJAX Request
  $.ajax({
   url: 'remover-dados.php',
   type: 'POST',
   data: { id:deleteid },
// here    ^^

   success: function(response){

    // Removing row from HTML Table
    $(el).closest('tr').css('background','tomato');
    $(el).closest('tr').fadeOut(800, function(){ 
     $(this).remove();
    });

   }
  });

So your PHP should be looking for that parameter value in $_POST['id'] 因此,您的PHP应该在$_POST['id']寻找该参数值

$id = $_POST['id'];

只需更换

$id = $_POST['id'];

Try this- 尝试这个-

$id = mysql_real_escape_string($_POST['id']);
$query ="DELETE FROM $datatable  WHERE id_avaria='$id'";
mysqli_query($con,$query);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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