2014-01-11 152 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看起来相当完美。 –