javascript - MySQL 和 PHP : Loop through table find value if it exists update if not insert new value

标签 javascript php mysql

我的数据库中的表如下所示:

http://abload.de/img/bildschirmfoto2014-07osj75.png

我需要 php 中的一个函数,它循环遍历表并在“翻译”列中查找提交的值,如果该值已存在,则应更新计数值 +1,如果不插入新行。

我希望有人能帮助我,因为我的 PHP 技能不是最好的。

这是我到目前为止尝试过的:

Javascript 代码:

var insertNewTranslation = function(word, translation) { 
    console.log("DBController, " +word+ " " + translation);

        $.ajax({
        type: 'GET',
        url: 'themes/tagging-theme/php/insertTranslation.php',
        data: {
                aktuelleswort: translation,
                uebersetzung: word
                },
        dataType: 'json',
        success : function(data){
            var tableNamen = data;
            console.log(tableNamen)



        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            console.log("XMLHttpRequest", XMLHttpRequest);
            console.log("textStatus", textStatus);
            console.log("errorThrown", errorThrown);    
        }
    });

};

php 文件如下所示:

<?php  
if( isset($_POST['aktuelleswort']) ) {
     $table=$_POST['aktuelleswort'];
}
else {
     $table="default";
}
if( isset($_POST['uebersetzung']) ) {
     $translation=$_POST['uebersetzung'];
}
else {
     $translation="default";
}


$con = mysql_connect('localhost', 'root', 'root');
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("bayerisches_lexikon", $con);

$sql = "SELECT _id, Translations, Count FROM $table";

$result = mysql_query($sql) OR die(mysql_error());
while ($row = mysql_fetch_assoc($result))
    $uebersetzungen[] = $row;

// mysql_query("INSERT INTO `bayerisches_lexikon`.`$table` (`Translations`, `Count`) 
//   VALUES ('" . $translation . "', '" . $count . "');");

mysql_close($con);

?>

最佳答案

您需要在“翻译”列上设置唯一键。然后使用

insert into mytable (translations, count) values ('gewurztraminer',1) on duplicate key update count=count+1

根本不是 php。

关于javascript - MySQL 和 PHP : Loop through table find value if it exists update if not insert new value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24510502/

相关文章:

mysql - 是否可以通过 ssl 将 typeorm 连接到 sql gcloud 的实例?

javascript - Firefox 扩展与 Greasemonkey 脚本?

PHP:帮助根据数据库中的 url 重定向重定向用户

javascript - 如何使用setInterval更新D3轮廓?

php - 在函数内部使用 switch,是否应该在 return true 之后使用 break?

php - Ajax 脚本将 xml 延迟加载到 div 中

javascript - 如何将动态 JS 文件传递​​到 PhantomJS

mysql - SQL获取与另一个产品具有更多共同属性的产品

javascript - jQuery.post动态数据回调函数

JavaScript 和德沃夏克 : Is there a way to get the key pressed rather than the character?