简体   繁体   中英

AJAX/Jquery not deleting row from MySQL table

I am trying to use AJAX and jQuery to delete a record from a table. The row is being removed from the page view as required, but not from the table.

Im using the following files and related sections:

Query

$result = mysql_query("SELECT id,name FROM myTable");

Query result:

while($row = mysql_fetch_array($result))
{
$id1=$row['id'];
$dataname=$row['name'];
?>
<div class="show">
<span class="name"><?php echo $dataname;  ?></span><br><span class="name"><?php echo $id1;  ?></span>
<span class="action"><a href="#" id="<?php echo $id1; ?>" class="delete" title="Delete">Delete</a></span>
</div>
<?php
}
?>

AJAX Script

<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this?"))
{
 $.ajax({
   type: "POST",
   url: "delete.php",
   data: info,
   success: function(){
 }
});
  $(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
  .animate({ opacity: "hide" }, "slow");
 }
return false;
});
});
</script>

delete.php

<?php
include('db.php');
if($_POST['id'])
{
$id=mysql_real_escape_string($_POST['id']);
$delete = "DELETE FROM `testdb` WHERE id = '$id1' ";
mysql_query($delete);
}
?>
$id=mysql_real_escape_string($_POST['id']);
$delete = "DELETE FROM `testdb` WHERE id = '$id1' ";

You are using $id1 in the delete statement, it should be $id

$delete = "DELETE FROM `testdb` WHERE id = '$id'";

NOTE : Your code is vulnerable to sql injection, start using preparedStatement with mysqli_ or PDO

UPDATE: Using PDO to do the delete operation

error_reporting(E_ALL);
ini_set('display_errors', '1');
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', '****', '****');
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
$id = $_POST['id'] ;
$sql = "DELETE FROM testdb WHERE id = :id "; 
$stmt = $pdo->prepare($sql); 
$stmt->bindParam(':id', $id, PDO::PARAM_INT); 
$stmt->execute(); 

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