如何使用AJAX删除mySql表行

时间:2016-06-17 19:05:44

标签: php jquery mysql

var table = "users";
var id = 25;

$("#btndel").click(function() {
    if (confirm("Are you sure ?")) {
        $.ajax({
            url: 'ajaxdel.php',
            type: 'post',
            data: {
                'table': 'table', 
                'id': 'id'
            },
            success: function() {
                location.href = "index.php";
            }
        })
    }
});

ajaxdel.php

extract($_POST);
$stmt = $db->prepare('DELETE FROM '.$table. ' WHERE id = :id') ;
$stmt->execute(array(':id' => $id));

表行未删除。

2 个答案:

答案 0 :(得分:2)

首先,您将字符串'table''id'作为POST参数传递,而不是相应变量的内容:

data: {'table': 'table', 'id': 'id'},

相反,您希望传递变量值:

data: {'table': table, 'id': id},

在将代码放在生产系统附近的任何地方之前,您还应该非常认真地考虑可能存在的漏洞。

答案 1 :(得分:1)

TimoSta的答案很好。但我在评论中看到它仍然无效。

所以这是你可以尝试PHP的东西 传递表名是一种更安全的方式。

我假设您使用SQL用户/ pass / DBname AND 定义了$db,您使用的SQL用户具有DELETE特权。

$tableArr=["users"];    // You may add other table names you want to access.

if(in_array($_POST['table'],$tableArr){

    $stmt = $db->prepare('DELETE FROM '.$_POST['table'].' WHERE id = ?') ;
    $stmt->bindParam(1,$_POST['id']);
    $stmt->execute;
}