2014-01-11 213 views
0

我試圖用PHP刪除SQL數據庫中的一行。 行由該產品的名稱,用戶類型決定SQL + AJAX + PHP POST請求

我創建了一個簡單的表格,刪除已經輸入產品:

<article> 
    <section> 

     <fieldset><legend><span>Would you like to add a Product?</span> </legend> 

     <form method="POST" id = "myForm" name="myForm" onsubmit="return  false;"> 

     <br> &nbsp; 

     <p>Enter a name of product <input type='text' id='name' name =  'name'/></p> 

     <br> &nbsp; 

    <input name="submit" id ="submit" type="button" value="Find Product"/> 

     </form> 
     </fieldset> 

     <div id="fetchProduct"> 
     </div> 

    </section> 
</article> 

說我已經進入了數據在另一種形式,它進入數據庫,但當我嘗試刪除它時,我收到未定義的索引:錯誤名稱,當我嘗試刪除。

下面是使用中刪除的產品腳本IM:

<?php 

include("database/connect_database.php"); 


    $name = $_POST['name']; 


$query = "DELETE FROM products WHERE product_name = '$name' "; 

$result = $database->query($query) OR die ("Failed query $query"); 
echo $database->error."<p>"; 

if($result){ 

    echo "Record deleted"; 
} 
else { 

    echo "Product not found!"; 
} 

?> 

林還使用AJAX通過名稱:

fetch = function() { 

// declare the two variables that will be used 
var xhr, target, changeListener; 

// find the element that should be updated 
target = document.getElementById("fetchProduct"); 

var name = document.getElementById("name").value; 

var variable = "name="+name; 

// create a request object 
xhr = new XMLHttpRequest(); 

changeListener = function() { 
    if (xhr.readyState === 4 && xhr.status === 200) { 

     target.innerHTML = xhr.responseText; 
    } else { 
     target.innerHTML = "<p>Something went wrong.</p>"; 
    } 
}; 

xhr.open("POST", "deleteProductSQL.php", true); 
xhr.onreadystatechange = changeListener; 
xhr.send(variable); 

}; 


pageLoaded = function() { 
var fetchButton = document.getElementById("submit"); 
if (fetchButton) { 
    fetchButton.addEventListener("click", fetch); 
} 
}; 

window.onload = pageLoaded; 

誰能指出哪裏我去可怕的錯誤在這裏,因爲我只是不能確定爲什麼它不允許我刪除該行,爲什麼我會收到未定義的錯誤。

謝謝你們的時間

+0

可愛[SQL注入攻擊](http://bobby-tables.com)漏洞。享受你的服務器pwn3d。 –

回答

0

把你的PHP代碼中isset()函數

if (isset($_POST['name']){ 
//code here 
} 

而且

<p>Enter a name of product <input type='text' id='name' name = 'name'/></p> 

在這一行,<p>不是自閉標籤所以

<p>Enter a name of product <input type='text' id='name' name = 'name'></p> 
+0

我試過了,錯誤消息已經消失,但它沒有通過任何東西,值是通過爲空?感謝您的幫助 – user3180997

+0

其實,我已經從jQuery學到了AJAX,所以我無法幫助您使用JS代碼。否則,你的PHP看起來相當完美。 –