我的MySQLi不会只更新插入?我的剧本出了什么问题?

时间:2015-02-19 18:44:07

标签: php mysql mysqli

    $check_verified_user = mysqli_query("SELECT * from user_verified where user_mail = '$payer_email'");
    $user_verified = mysqli_fetch_array(mysqli_query($conDB, "SELECT * FROM user_verified where user_mail = '$payer_email'"));

    if(mysqli_num_rows($check_verified_user) > 0) {
        mysqli_query($conDB, "UPDATE user_verified SET total_paid = total_paid + '$payment_amount' where user_mail = '$payer_email'");
    } else {
        mysqli_query($conDB, "INSERT into user_verified (user_mail,total_paid) VALUES ('$payer_email', '$payment_amount')");
    }

我不知道我的脚本有什么问题,它检查该行是否存在,如果它存在则应该更新,但是它会插入另一行,我不明白......

3 个答案:

答案 0 :(得分:0)

试一试。

$query = "SELECT * FROM user_verified WHERE user_mail = $payer_email";
$check_verified_user = mysqli_query($conDB, $query);

你基本上没有给它数据库连接,因此总是回来时不会超过0行。就个人而言,我总是先将查询放入自己的变量中,这样可以确保您不会忘记mysqli_query()函数的参数。它还使阅读更容易,并允许您在需要时在其他地方使用查询。

答案 1 :(得分:0)

你可以这样做:

$sql = "SELECT * from user_verified where user_mail = '$payer_email'";
$result = mysqli_query($conDB, $sql) or trigger_error(mysqli_error($conDB));    

if (mysqli_num_rows($result)) {
  $sql = "UPDATE user_verified SET total_paid = total_paid + '$payment_amount' where user_mail = '$payer_email'";
}
else {
  $sql = "INSERT into user_verified (user_mail,total_paid) VALUES ('$payer_email', '$payment_amount')";
}

mysqli_free_result($result);
mysqli_query($conDB, $sql) or trigger_error(mysqli_error($conDB));    

答案 2 :(得分:0)

如果您的user_mail是UNIQUE KEY,您可以在INSERT中使用ON DUPLICATE KEY UPDATE选项。您只需1次查询即可完成所有操作。

$sql = "INSERT INTO user_verified (user_mail,total_paid) VALUES ('$payer_email',$payment_amount) ON DUPLICATE KEY UPDATE total_paid = total_paid + $payment_amount";

mysqli_query($conDB, $sql);

使用UNIQUE KEY检查此表的示例。

http://sqlfiddle.com/#!2/4919e2/1/0