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

4

我正在尝试使用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);
}
?>

您的删除查询存在注入漏洞,请使用绑定(即:正确准备它)。请参见:http://php.net/manual/zh/pdo.prepare.php - KIKO Software
请养成接受答案的习惯,https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work。这个问题仍在等待接受,https://stackoverflow.com/questions/45654837/how-do-i-redirect-a-form-after-submission-to-the-same-page。 - chris85
抱歉,我是新来的,我不知道那个......我会记住的。 - Logan 96
@ARIJITDASGUPTA 你仍然可以接受那个问题的答案。前往该问题,滚动到答案处,点击复选标记(假设它根据评论回答了你的问题)。 - chris85
1个回答

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

它已经可以工作了,谢谢@chris85。如何删除图像的预览? - Logan 96
我不知道预览是什么?你的意思是从发送 AJAX 的页面中删除它吗? - chris85
是的..我的意思是在那个页面上我已经获取了上传的图像..然后我创建了一个删除按钮来从数据库中删除记录..我想要同时删除预览..@chris - Logan 96
不要使用alert("Image Deleted from database");,而是使用类似于$('#image').attr('display', 'none');的代码。这是一个JS/CSS问题/问题,与PHP无关。 - chris85

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接