PHP通过AJAX删除MySQL行

时间:2012-08-25 18:29:27

标签: php mysql ajax

我正在尝试通过Ajax删除MySQL表行。奇怪的是,它只在部分时间起作用。有时我必须在它工作之前点击删除按钮2-3次,否则无论我点击多少次都无法工作。其他时候,我只需点击一次即可。

Ajax代码

function ajax() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest(); //IE7+, FF, Chrome, Opera, Safari
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE6, IE5
    }
    return xmlhttp;
}

function deleteTransaction(id) {
    var xmlhttp = ajax();
    var url = "../php/deletetransaction.php";
    url += "?id=" + id;
    url += "&sid=" + Math.random();

    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);
}

deletetransaction.php

<?php 
include_once("connect.php");
include_once("functions.php");

$id = $_GET['id'];

$query = "SELECT * FROM transactions WHERE id='$id'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_assoc($result);

$type = $row['type'];
$room = $row['roomid'];
$roommates = getRoommates($room);
$total = $row['total'];
$split = getSplit($id);

$purchaser = $row['purchaser'];
for ($i=0; $i<count($roommates); $i++) {
    $user = $roommates[$i];
    $oldBalance = getBalance($user);
    $newBalance = $oldBalance;
    if ($user == $purchaser) {
        $newBalance -= $total;
    }
    $newBalance += $split[$user];

    $query = "UPDATE users SET balance='$newBalance' WHERE id='$user'";
    mysql_query($query) or die(mysql_error());
}

$query = "DELETE FROM transactions WHERE id='$id'";
mysql_query($query) or die(mysql_error());
?>

我一直绞尽脑汁想弄清楚为什么会这样。我检查了我的代码,它确实到达了我的PHP文档中的最后一个$查询,并输出了语法上正确的MySQL删除查询。关于为什么这不能持续发挥作用的任何想法?

感谢您的所有帮助!

0 个答案:

没有答案