0

If there exists a row in the table FINES with the required value then I just want to update the fields Else I want to add a new row in the table.

if (mysql_query("SELECT EXISTS(SELECT * FROM fines WHERE SId='$sid' AND Semester='$sem')")>=1)

 mysql_query("UPDATE fines SET fines.TFine=fines.TFine+'$fine' WHERE SId='$sid' AND Semester='$sem'");           

else

   mysql_query("INSERT INTO fines(SId, Semester, TFine, Flag) VAlUES('$sid','$sem', '$fine', 0)");

But the if condition is not working!! Please help

4

1 回答 1

1

INSERT ... ON DUPLICATE KEY UPDATE如果记录已经存在,则使用 MySQL更新记录,如果不存在则插入。

您需要做的第一件事是unique在一个或多个列上指定一个约束,

ALTER TABLE fines ADD CONSTRAINT tb_uq UNIQUE (SId, Semester)

一旦你执行了语句,你可以简单地创建一个这样的语句,

INSERT INTO fines(SId, Semester, TFine, Flag) 
VALUES ('$sid','$sem', '$fine', 0)
ON DUPLICATE KEY UPDATE TFine = TFine +  '$fine';
于 2013-03-24T11:49:31.090 回答