简体   繁体   中英

MySQL and PHP: Loop through table find value if it exists update if not insert new value

the tables in my Database look like this:

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

I need a function in php which loops through the table and finds the committed value in the "Translations" Column, if the value already exists it should update the Count value +1, if not insert a new row.

I hope someone can help me, because my PHP skills are not the best.

This is what I tried so far:

The Javascript Code:

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);    
        }
    });

};

The php File looks like this:

<?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);

?>

You need to set a unique key on the "Translation" column. Then use

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

Not php at all.

mysqli_num_rows()

You'll use the above function; if it returns 0 you'll do an INSERT; if it doesn't you'll perform an UPDATE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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