使用ajax和php从数据库中删除图像

时间:2017-08-27 18:41:07

标签: php mysql ajax

我正在尝试使用ajax删除图像。它显示了数据已被删除的警告消息,但在表中记录已存在。如何从表格中删除图像记录....

<span><input type="submit" id="del_btn" value="Delete Image" /></span>
<script type="text/javascript">
$(document).ready(function () {
    $("input#del_btn").click(function(){
         $.ajax({
             type: "POST",
             url: "del.php", // 
             data: {id: <?php echo $delid; ?>},
             success: function(msg){
             alert("Image Deleted from database");  
             },
             error: function(){
             alert("failure");
           }
           });
        });
    });
  </script>

这是del.php

<?php
if (isset($_POST['id'])) {
    $imgid = $_POST['id'];
    $con=new PDO("mysql:host=localhost;dbname=newimg","root","");
    $sql = "DELETE FROM attempt010 WHERE id='$imgid' ";
    $con->execute($sql);
}
?>

1 个答案:

答案 0 :(得分:0)

PDO execute函数执行预准备语句。所以你需要准备然后执行。还应准备好准备好的陈述。尝试:

if (isset($_POST['id'])) {
    $imgid = $_POST['id'];
    $con=new PDO("mysql:host=localhost;dbname=newimg","root","");
    $sql = "DELETE FROM attempt010 WHERE id=?";
    $stmt = $con->prepare($sql);
    $stmt->execute(array($imgid));
}

有关详细信息,请参阅:

  1. http://php.net/manual/en/pdostatement.execute.php
  2. http://php.net/manual/en/pdo.prepare.php
  3. http://php.net/manual/en/pdo.prepared-statements.php