通过jquery和php删除MySQL记录

时间:2014-07-02 15:22:35

标签: php jquery mysql ajax

我无法弄清楚为什么这段代码不起作用。我希望能够单击adminSLP页面中的删除按钮,当我这样做时将弹出一个确认对话框。之后,如果用户单击“确定”,它将从数据库中删除该记录。

是否有更简单的解决方案或我缺少的东西?我尝试从中删除的表格为users,其id列为user_id

adminSLP

<a href="#" class="delete">Delete</a>

jquery的

$(".delete").click(function(){
    var user_id = element.attr("id");
    var info = 'id=' + user_id;
    if(confirm("Sure you want to delete this update? There is NO undo!"))
    {
    $.ajax({
    type: "POST",
    url: "delete.php",
    data: info,
    success: function(){
    }
    });
    $(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
    .animate({ opacity: "hide" }, "slow");
    }
    return false;
    });

delete.php

<?php
// Initializing connection data.
$host_db = 'DB';
$name_db = 'NAME';
$user_db = 'USER';
$pass_db = '*******';

// Connecting using the PDO object.
$connection = new PDO("mysql:host=$host_db; dbname=$name_db", $user_db, $pass_db);

// Setting the query and runnin it...

$states = "SELECT * FROM license_state";
$array = array();
$result = $connection->query($select);
if(!isset($_GET['delete'])){
    $id = $_GET['delete'];
    $sql= "DELETE FROM users WHERE user_id=$user_id";
    $result=mysqli_query($sql,$connection);
}
?>

1 个答案:

答案 0 :(得分:1)

应该是这样的:

<强> delete.php

...
$connection = new PDO("mysql:host=$host_db; dbname=$name_db", $user_db, $pass_db);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if (isset($_POST['id']) && is_numeric($_POST['id'])) {
    $user_id = $_POST['id'];
    $sql = "DELETE FROM users WHERE user_id = :user_id";
    $query = $connection->prepare($sql);
    $query->bindParam(':user_id', $user_id, PDO::PARAM_INT);
    $query->execute();
}

你的代码太乱了。您应该阅读有关您问题的所有评论,因为它可以帮助您稍后编写更好的代码。希望它有所帮助:)