At first I tried to do the SQL-Query with IF NOT EXISTS
, but I got always a Syntax Error and didn't really understand why. But typing in my title stackoverflow gave me some questions concerning the same issue. Interesting enough Google wasn't able to find them... Whatever, so I changed the query into what Mike suggested in this Question.
Now I have the following code snippet:
$tblTeam = "INSERT INTO tblTeam (nameTeam, nationID)
SELECT * FROM (SELECT '" . $match_Team[1] . "', (SELECT nationID FROM tblNation WHERE nameNation = '" . $nation_name[1] . "')) AS tmp
WHERE NOT EXISTS (
SELECT nameTeam FROM tblTeam WHERE nameTeam = '" . $match_Team[1] . "'
) LIMIT 1;
INSERT INTO tblTeam (nameTeam, nationID)
SELECT * FROM (SELECT '" . $match_Team[2] . "', (SELECT nationID FROM tblNation WHERE nameNation = '" . $nation_name[2] . "')) AS tmp
WHERE NOT EXISTS (
SELECT nameTeam FROM tblTeam WHERE nameTeam = '" . $match_Team[2] . "'
) LIMIT 1;";
If I run that query with pure SQL syntax directly in phpMyAdmin everything is fine, I get my entries in tblTeam
. But as soon as I try to do that by PHP I get the following Syntax Error:
Error description tblTeam:
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 'INSERT INTO tblTeam (nameTeam, nationID) SELECT * FROM (SELECT 'B' at line 7
I'm a bit confuse now because I don't see what's the issue. In my used example for debugging $match_Team[1]
has the value Serbia
, $match_Team[2]
the value Brazil
. Same goes for $nation_name[1]
and $nation_name[2]
respectively.
EDIT: Because @FDavidov asked for it, here's the content of $tblTeam:
INSERT INTO tblTeam (nameTeam, nationID) SELECT * FROM (SELECT 'Serbia', (SELECT nationID FROM tblNation WHERE nameNation = 'Serbia')) AS tmp WHERE NOT EXISTS (SELECT nameTeam FROM tblTeam WHERE nameTeam = 'Serbia') LIMIT 1; INSERT INTO tblTeam (nameTeam, nationID) SELECT * FROM (SELECT 'Brazil', (SELECT nationID FROM tblNation WHERE nameNation = 'Brazil')) AS tmp WHERE NOT EXISTS (SELECT nameTeam FROM tblTeam WHERE nameTeam = 'Brazil') LIMIT 1;