A couple comments on the SQL. One, is that syntax valid? I don't know mysql, but "SELECT IF NOT EXISTS" is not valid SQL. EXISTS() returns a binary value and thus must be used in a WHERE clause or CASE expression. SELECT ... WHERE EXISTS() is the standard method. If that is an IF statement instead, the SELECT would appear later: IF EXISTS() THEN SELECT ... ELSE INSERT....
Two, the query is using variables to put create a dynamic SQL statement. Dynamic SQL is generally considered insecure. But, it can be easily avoided via placeholders and passing the values in the execute() statement.