2017-08-27 56 views
3

我想使用ajax刪除圖像。它顯示警報消息,表明數據已被刪除,但表中的記錄在那裏。我怎樣才能從表中刪除圖像記錄....使用ajax和php從數據庫中刪除圖像

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

你刪除查詢爲您開放,注射,請使用綁定(即:準備它正確)。看到; http://php.net/manual/en/pdo.prepare.php –

+0

也請接受回答的習慣,https://meta.stackexchange.com/questions/5234/how-does-accepting-an-回答工作。這個問題仍在等待接受,https://stackoverflow.com/questions/45654837/how-do-i-redirect-a-form-after-submission-to-the-same-page。 – chris85

+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
+0

它的工作謝謝你@ chris85 ..我怎樣才能刪除圖像的預覽? –

+0

我不知道,預覽是什麼?你的意思是在AJAX發送的頁面上刪除它嗎? – chris85

+0

是的..我的意思是在那個頁面中我已經提取了上傳的圖像..因爲我已經創建了刪除按鈕以從數據庫中刪除記錄..我也刪除了預覽... @chris –

相關問題