WPDB如果主键已存在,则在整型字段中添加+1

时间:2022-02-21 作者:user44109

我需要一个检查主键(字符串)是否已经存在的系统。

如果是,那么我想在第二列中添加1。

如果没有,那么我想添加一个新行,并将第二列的值设置为1。

以下是我的尝试:

$foodWishNameStr = ($_POST["foodWishName"]);

$foodWishPoint = 1;


$sanitized_foodWish = sanitize_text_field($foodWishNameStr); /* Checks for problematic things in the string like invalid UTF-8, it converts < characters to entities, strips all tags, removes line breaks, tabs and extra white space. */


global $wpdb;


    //my column names in the table are foodWishName and foodWishPoints:
    $sql = "INSERT INTO foodWishes (foodWishName,foodWishPoints) VALUES (%s,%d) ON DUPLICATE KEY UPDATE foodWishPoints + 1 = %d";
    // var_dump($sql); // debug
    $sql = $wpdb->prepare($sql,$sanitized_foodWish,$foodWishPoint, $foodWishPoint);
    // var_dump($sql); // debug
    $wpdb->query($sql);

    if($sql){ //return the response
        echo $sql;
    }else{
    echo "something went very wrong";
    }

    exit();
这给了我一个错误:

<div id="error"><p class="wpdberror"><strong>WordPress database error:</strong> [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near &#039;+ 1 = 1&#039; at line 1]<br /><code>INSERT INTO foodWishes (foodWishName,foodWishPoints) VALUES (&#039;redwinevinegar&#039;,1) ON DUPLICATE KEY UPDATE foodWishPoints + 1 = 1</code></p></div>INSERT INTO foodWishes (foodWishName,foodWishPoints) VALUES (\'redwinevinegar\',1) ON DUPLICATE KEY UPDATE foodWishPoints + 1 = 1

1 个回复
最合适的回答,由SO网友:user44109 整理而成

在我的案例中,这是正确的公式:

$sql = "INSERT INTO foodWishes(foodWishName,foodWishPoints) VALUES (%s,%d) ON DUPLICATE KEY UPDATE foodWishPoints = foodWishPoints +1";
    // var_dump($sql); // debug
    $sql = $wpdb->prepare($sql,$sanitized_foodWish,$foodWishPoint,);
    // var_dump($sql); // debug
    $wpdb->query($sql);

    if($sql){ //return the response
        echo $sql;
    }else{
    echo "something went very very wrong";
    }

    exit();