if (isset($_POST["sendComments"]) ) {
$whichProjectToSave= mysqli_real_escape_string($db5, $_POST['whichProjectToSave']);
$commentsToPHP= mysqli_real_escape_string($db5, $_POST['commentsToPHP']);
$objectName= mysqli_real_escape_string($db5, $_POST['objectName']);
$sql="INSERT INTO objectsCommentsTable (objectsCommentsText,projectName,objectName) VALUES('$commentsToPHP','$whichProjectToSave','$objectName')";
// $sql="UPDATE objectsCommentsTable SET objectsCommentsText ='$commentsToPHP' WHERE projectName= '$whichProjectToSave' AND objectName = '$objectName' ";
mysqli_query($db5,$sql);
}
如果数据存在,我必须更新。但我只知道如何使用上面的方法。 实际上我只能在表格中插入数据,然后通过更改代码来更新它。但我想使用类似下面的代码。如何进行?
IF EXISTS ( SELECT objectsCommentsText FROM objectsCommentsTable WHERE objectName='$objectName' AND projectName = '$projectName')
UPDATE objectsCommentsTable
SET objectsCommentsText ='$commentsToPHP'
WHERE projectName= '$whichProjectToSave' AND objectName = '$objectName'
ELSE
INSERT INTO objectsCommentsTable (objectsCommentsText,projectName,objectName)
VALUES('$commentsToPHP','$whichProjectToSave','$objectName')
答案 0 :(得分:3)
首先,添加唯一索引:
ALTER TABLE objectsCommentsTable ADD UNIQUE project_object_unique (projectName, objectName);
这将阻止添加具有相同 projectName 和 objectName 的行,并使 ON DUPLICATE 工作。
然后,您可以修改查询以使用 ON DUPLICATE
INSERT INTO objectsCommentsTable
(objectsCommentsText, projectName, objectName) VALUES ('$commentsToPHP','$whichProjectToSave', '$objectName')
ON DUPLICATE KEY
UPDATE objectsCommentsText='$commentsToPHP'
答案 1 :(得分:1)
您必须使用此方法INSERT ... ON DUPLICATE KEY UPDATE Syntax