I want to insert a record if it does not exist without using unique ID, and I found this answer here: MySQL: Insert record if not exists in table.
In my case I have a table:
+----+---------+---------+---------+---------+-----------+-------------+-----------+
| ID | dRelIns | vRelIns | dRelDel | vRelDel | cRelAktiv | iRelDateiId | iRelKatId |
+----+---------+---------+---------+---------+-----------+-------------+-----------+
| 1 | blabla | blabla | NULL | NULL | J | 3 | 5 |
+----+---------+---------+---------+---------+-----------+-------------+-----------+
| 2 | blabla | blabla | blabla | blabla | N | 3 | 1 |
+----+---------+---------+---------+---------+-----------+-------------+-----------+
| 3 | blabla | blabla | NULL | NULL | J | 3 | 2 |
+----+---------+---------+---------+---------+-----------+-------------+-----------+
I am getting an array ($_POST) with id iRelKatId and another on id iRelDateiId. I check if the id already exists and cRelAktiv = 'J', if not I want to insert a new one. If some entry exists but it's not in the list, I want to set cRelAktiv to 'N'.
My PHP script with the SQL queries:
$list=implode("','", $_POST["kat"]);
$sql="UPDATE tabRel_UDK SET dRelDel=NOW(),
vRelDel=USER(),
cRelAktiv='N'
WHERE iRelDateiId='$_POST[id]' AND cRelAktiv='J' AND iRelKatId NOT IN('$list')";
$result = mysql_query($sql) or die(Error (" . mysql_error() . ").");
foreach ($_POST["kat"] as $value) {
$sql="INSERT INTO tabRel_UDK (dRelIns, vRelIns, cRelAktiv, iRelDateiId, iRelKatId)
SELECT * FROM (SELECT NOW(), USER(), 'J', '$_POST[id]','$value') AS tmp
WHERE NOT EXISTS (
SELECT iRelDateiId,iRelKatId,cRelAktiv FROM tabRel_UDK
WHERE iRelDateiId = '$_POST[id]' AND iRelKatId='$value' AND cRelAktiv='J') LIMIT 1;";
$result = mysql_query($sql) or die("Error (" . mysql_error() . ").");
}
This script works for me, but when both ids have the same value(for example 5), it throws an error Duplicate column name '5' because of SELECT * FROM (SELECT NOW(), USER(), 'J', '$_POST[id]','$value')
Any ideas how to make it works, or should I make 2-3 SQL queries and check the ids manually in PHP?