AJAX / Jquery不从MySQL表中删除行

时间:2014-05-09 19:34:13

标签: php jquery mysql ajax

我正在尝试使用AJAX和jQuery从表中删除记录。该行将根据需要从页面视图中删除,但不会从表中删除。

我正在使用以下文件和相关部分:

查询

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

查询结果:

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 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);
}
?>

1 个答案:

答案 0 :(得分:3)

$id=mysql_real_escape_string($_POST['id']);
$delete = "DELETE FROM `testdb` WHERE id = '$id1' ";

您在删除语句中使用$id1,它应该是$id

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

注意:您的代码易受sql注入攻击,开始使用   带有mysqli_PDO

的preparedStatement

更新:使用PDO执行删除操作

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();