简体   繁体   English

MySQL不能持续更新行?

[英]MySQL not updating row consistently?

I have the following code which sends an AJAX POST to a php file on my server to add a row into a MySQL table. 我有以下代码,它将AJAX POST发送到服务器上的php文件,以将行添加到MySQL表中。 This function gets run when a user marks an item as their favorite: 当用户将某项标记为自己的收藏夹时,将运行此函数:

$.ajax({
    type: 'POST',
    data: 'school='+school+'&token='+token,
    url: 'http://www.codekraken.com/testing/snowday/database9.php',
    success: function(data){
    console.log(data);
    },
    error: function(){
    console.log(data);
    }
 });

I also have a similar function that runs when they delete the favorite: 当他们删除收藏夹时,我还有一个类似的功能可以运行:

data: 'school=&token='+token,

This works, but not consistently. 这可行,但不一致。 The PHP code is below: PHP代码如下:

<?php
$server = "localhost";
$username = "";
$password = "";
$database = "";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());

mysql_select_db($database, $con);

$token = $_POST["token"];
$school = $_POST["school"];

if (strlen($token) == 0){
    die('Incorrect token');
}

if (strlen($school) == 0){
    die('Invalid school name');
}

$sql = "INSERT INTO Snow (Token, School, Skip) ";
$sql .= "VALUES ('$token', '$school', '0') ON DUPLICATE KEY UPDATE School='$school'";

if (!mysql_query($sql, $con)) {
    die('Error: ' . mysql_error());
} else {
    echo "$token, $school = Success";
}

mysql_close($con);
?>

What I mean by it not working consistently is that if I mark one item as the favorite, it will create a row. 我的意思是,如果我将某一项标记为收藏夹,它将无法创建行。 If I unmark it, it will change $school to nothing. 如果我取消标记,它将使$school变为零。 If I then mark a different item, it will change to that item. 如果我再标记其他项目,它将更改为该项目。 IF , however, I try marking the first item as a favorite, it won't update, but will retain the last change. 但是, 如果我尝试标志着第一项为收藏,不会更新,但将保留最后的修改。

So, it seems that it's only updating the row each time something new happens, but not if the value has already been present even though it's not CURRENTLY present. 因此,似乎每次发生新情况时都仅更新该行,但即使该值不存在,即使该值已经存在也不会更新。

NOTE: Column Token is indexed as a UNIQUE PRIMARY 注意:Token被索引为UNIQUE PRIMARY索引

The JS code that pertains to var school : var school有关的JS代码:

function setFavorite() {
    var threshold = {
        x: 30,
        y: 10
    };
    var originalCoord = {
        x: 0,
        y: 0
    };
    var finalCoord = {
        x: 0,
        y: 0
    };

    function touchMove() {
        finalCoord.x = event.targetTouches[0].pageX;
        changeX = originalCoord.x - finalCoord.x;
        var changeY = originalCoord.y - finalCoord.y;
        if (changeY < threshold.y && changeY > (threshold.y * -1)) {
            changeX = originalCoord.x - finalCoord.x;
            if (changeX > threshold.x) {
                window.removeEventListener('touchmove', touchMove, false);
                $(document).off("touchmove", ".row");
                if ($(event.target).attr("class") === "row-inside") {
                    var element = $(event.target);
                }
                if ($(event.target).attr("class") === "row-l") {
                    var element = $(event.target).parent();
                }
                if ($(event.target).attr("class") === "row-r") {
                    var element = $(event.target).parent();
                }
                var text = $(element).find(".row-l").text();

                var token = window.deviceToken;
                var school = $(element).find(".row-l").text();

                var favstatus = $(element).find(".row-r").text();
                var thisStar = $(element).parent().find(".star-inside");
                $(element).css("margin-left", "-75px");
                if ($(thisStar).hasClass("favorite")) {
                    $.ajax({
                        type: 'POST',
                        data: 'school=&token=' + token,
                        url: 'http://www.codekraken.com/testing/snowday/database10.php',
                        success: function (data) {
                            console.log(data);
                        },
                        error: function () {
                            console.log(data);
                        }
                    });
                    $(".clear span").text("");
                    $(thisStar).removeClass("favorite");
                    localStorage.removeItem("favorite");
                    localStorage.removeItem("favorite-status");
                } else {
                    $.ajax({
                        type: 'POST',
                        data: 'school=' + school + '&token=' + token,
                        url: 'http://www.codekraken.com/testing/snowday/database10.php',
                        success: function (data) {
                            console.log(data);
                        },
                        error: function () {
                            console.log(data);
                        }
                    });
                    $(".clear span").text("\"" + text + "\"");
                    localStorage.setItem("favorite", text);
                    localStorage.setItem("favorite-status", favstatus);
                    $(".star-inside").not(thisStar).removeClass("favorite");
                    $(thisStar).addClass("favorite");
                }
                setTimeout(function () {
                    $(element).css("margin-left", "0px");
                }, 500);
                setTimeout(function () {
                    $(document).on("touchmove", ".row", function () {
                        touchMove();
                    });
                }, 800);
            }
        }
    }

    function touchStart() {
        originalCoord.x = event.targetTouches[0].pageX;
        finalCoord.x = originalCoord.x;
    }
    $(document).on("touchmove", ".row", function () {
        touchMove();
    });
    $(document).on("touchstart", ".row", function () {
        touchStart();
    });
}

MySQL Output: MySQL输出:

CREATE TABLE `Snow` (
 `Token` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
 `School` text COLLATE utf8_unicode_ci NOT NULL,
 `Skip` int(1) NOT NULL,
 PRIMARY KEY (`Token`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicod

I figured it out. 我想到了。

The problem seemed to be with Phonegap caching the AJAX request. 问题似乎与Phonegap缓存AJAX请求有关。 I then thought if I added cache: false, to the AJAX request, it would solve it, but once again, no dice. 然后,我想如果我向AJAX请求中添加cache: false,它将解决该问题,但是再一次,没有骰子。

I then googled around a bit, and found the piece of code that made it work: 然后,我在谷歌上搜索了一下,找到了使它起作用的代码:

beforeSend: function(xhr) { xhr.setRequestHeader("Cache-Control", "no-cache"); xhr.setRequestHeader("pragma", "no-cache"); },

You put that within your AJAX request, so it would look something like: 您将其放入您的AJAX请求中,因此看起来像:

$.ajax({
    cache: false,
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Cache-Control", "no-cache");
        xhr.setRequestHeader("pragma", "no-cache");
    },
    type: 'POST',
    ...
});

I'm not entirely sure if it can work without also setting cache: false , but I don't feel like rocking the boat. 我不完全确定是否也可以不设置cache: false来工作cache: false ,但是我不喜欢摇晃船。 I also specified within my PHP code these headers: 我还在PHP代码中指定了以下标头:

header("Expires: Tue, 01 Jul 2001 06:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

Turns out the immediate above is not nescesary, but I'll leave it here in case it helps someone else. 原来上面的内容不是必需的,但是我将其保留在此处,以防其他人使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM