2013-10-09 81 views
-1

我正在使用ajax方法來調用一個PHP腳本,該腳本應該在點擊一個ID爲'delete'的按鈕後從我的數據庫中刪除一行。MySQL DELETE在PHP中不執行查詢

$('#delete').click(function() { 
    var id = parseInt($('#content').attr('data-name')); 
    // The row in my database has the type integer 
    // Doing alert(id) correctly returns the value 

$.ajax({ 
    url : './php/delete.php', 
    type: 'POST', 
    data : id, 
    success: function() 
    { 
     alert('success deleting ' + id); 
     location.reload(); 
     // These both get called correctly, but the row is not actually getting deleted 
    } 
}); 

}); 

我的PHP代碼是

<?php 
$con=mysqli_connect("localhost","root","tulula15","content_test"); 

if (mysqli_connect_errno()) 
    { 
echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

mysqli_query($con,"DELETE FROM htmlcontent WHERE id='$_POST[id]'"); 

mysqli_close($con); 
?> 

運行在phpMyAdmin同一查詢正確地刪除了該行

DELETE FROM htmlcontent WHERE id=2 

所以阿賈克斯成功返回,但沒有被執行的查詢。

如果有人可以幫助我解決這個問題我會非常感激..

+5

您極易受SQL注入影響。 –

+0

1.運行查詢時使用mysqli錯誤處理,並查看服務器日誌文件。 – arkascha

+0

使用prepare語句來參數化$ _POST ['id']變量 – aarryy

回答

4

您在AJAX調用中沒有正確設置數據。這樣做:

$.ajax({ 
    url : './php/delete.php', 
    type: 'POST', 
    data : {id:id},   // use a map like this to set up the POST data 
    success: function() 
    { 
    alert('success deleting ' + id); 
    location.reload(); 
    // These both get called correctly, but the row is not actually getting deleted 
    }  
}); 
+0

謝謝,這解決了它 –

+0

我認爲「bye bye htmlcontent」是真實的;( –

-3

您的查詢是不正確的。你並沒有逃離弦。你必須這樣做: 你也沒有concatonate變量的字符串。

mysqli_query($con,"DELETE FROM htmlcontent WHERE id='".$_POST[id]."'") 
+0

您*仍*不會轉義字符串。使用預準備語句來防止SQL注入。 –

+0

$ _POST ['id']等於「'OR'1'='1」? –

+0

@vp_arth bye bye html內容 –