【问题标题】:Row not being deleted in database when using AJAX and PHP使用 AJAX 和 PHP 时不会在数据库中删除行
【发布时间】:2016-03-26 05:48:43
【问题描述】:

我在我的应用程序上创建了一个按钮,该按钮应该删除我的数据库中的一条记录。目前我收到一条消息,说记录已成功删除,但实际上并没有删除它。

这是我的按钮 HTML

<button id="deleteButton" class="btn btn btn-danger btn-lg active" role="button" value="<?php echo $rows['recipe_id']; ?>">Delete Recipe</button>

我首先使用这段代码通过 ajax 发送记录的 ID

$(document).ready(function() {
    $('#deleteButton').click(function(){
        var clickBtnValue = $(this).val();
        var recipeID = JSON.stringify(clickBtnValue);
        var data = {
            "action" : recipeID
        }
        var ajaxurl = '/recipe-project/ajax.php';
        $.ajax({
            url: ajaxurl,
            type: "POST",
            data: data,
            success:function(data) {
                alert(data);
            }
        });
    });
});

这是我的 PHP

include_once('classes/class-database-functions.php');
include_once ('classes/User.php');

if (isset($_POST['action'])) {
    $recipe_id = $_POST['action'];
    $test = new User();
    if (!empty($test)) {
        $test->delete_recipe($recipe_id);
    }
}

这是类中实际删除记录的函数

public function delete_recipe($recipeID) {

        $query = "DELETE FROM recipes WHERE recipe_id= '$recipeID'";

        if (mysqli_query($this->connection, $query)) {
            echo "Record deleted successfully";
        } else {
            echo "Error deleting record: " . mysqli_error($this->connection);
        }
    }

我的日志中没有出现错误,并且我检查了 ajax 是否向函数发送了正确的 ID,任何人都知道为什么会出现这个问题吗?

【问题讨论】:

    标签: php jquery mysql ajax


    【解决方案1】:

    因为它是一个 POST,所以你的这部分代码很好:

    if (isset($_POST['action'])) {
        $recipe_id = $_POST['action'];
        $test = new User();
        if (!empty($test)) {
            $test->delete_recipe($recipe_id);
        }
    }
    

    但是为了你的调试,你可以在这段代码之前:

    var_dump($_POST);
    

    您也可以在 Firefox 上安装 firebug 以调试您发送的数据。

    【讨论】:

      【解决方案2】:

      我建议你把你的代码改成这个

      if (isset($_GET['action'])) {
          $recipe_id = $_GET['action'];
          $test = new User();
          if (!empty($test)) {
              $test->delete_recipe($recipe_id);
          }
      }
      

      然后通过直接在浏览器中访问 URL 并包含 $_GET 变量来测试它,例如?action=the recipe's id。然后你可以使用var_dump来调试ID是否正确,你的$test对象是否创建正确,查询是否执行正确。

      【讨论】:

        猜你喜欢
        • 2021-04-05
        • 2018-02-05
        • 2013-11-12
        • 2013-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-14
        • 1970-01-01
        相关资源
        最近更新 更多