我在应用程序上创建了一个按钮,用于删除数据库中的记录。目前,我收到一条消息,说记录已被成功删除,但实际上并没有删除。
这是我的按钮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,有人能理解为什么会出现这个问题吗?
因为这是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来调试你发送的数据。
我建议您将代码更改为这个
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
)来测试它。然后,如果ID正确、$test
对象创建正确以及查询执行正确,则可以使用var_dump
进行调试。