从数据库中删除行的AJAX不起作用

时间:2017-03-17 08:49:11

标签: php jquery mysql ajax

我想使用文本旁边的按钮删除数据库中具有文本输出的行。所以这是我的代码:

<?php
...

while ($finresult = mysqli_fetch_array($result)){
        if ($finresult['id'] == $id){
        print_r($finresult['email']);
        $print = $finresult['email'];

        echo '<p id="demo"> </p><button onclick="getElementById(\'demo\').innerHTML=myajax($print)">Delete</button>
            ';

?>

<html>

<script> 
        function myajax(id){

                $.ajax({
                    type: "POST",
                    url: "delete.php",
                    data: id
                    success: function(data){
                        if (data == id + "y"){
                            return "It works";
                        }
                        else{
                            return "Doesn't work";
                        }
                    }
                });


        }
</script>

</html>

这是delete.php

<?php 
$link = mysqli_connect("localhost","*****","****");
mysqli_select_db($link, 'form');

$id = $_POST['id'];

$query = "DELETE FROM Customers WHERE Customers.email = '$id'";
$result = mysqli_query($link, $query);
if (isset($result)){
    echo "y";
}
else{
    echo "n";
}
?>

如果有人能告诉我出了什么问题,我真的很感激。谢谢!

1 个答案:

答案 0 :(得分:0)

您必须用单引号括起函数调用参数:

echo '<p id="demo"></p>
      <button onclick="getElementById(\'demo\').innerHTML=myajax(\'' . $print . '\')">Delete</button>';

此外:

  1. 注意SQL注入。 Learn how to prevent it
  2. ID不是电子邮件,因此请相应地命名变量以帮助您了解将来的代码