我的数据库中的表如下所示:
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/