0

I need to insert data except if 2 fields exist in that row. Below is my current query that adds everything that works.

$sql = "INSERT INTO contact_sync_status (ghl_contact_email, ghl_contact_data, result, wp_user_id) VALUES ('$source->email', '$payload', 'success', $user->id)"; 

So I tried the following to make it conditional:

$sql = "INSERT INTO contact_sync_status (ghl_contact_email, ghl_contact_data, result, wp_user_id) VALUES ('$source->email', '$payload', 'success', $user->id) WHERE NOT EXISTS (SELECT 1 FROM contact_sync_status WHERE ghl_contact_email = '$source->email' AND wp_user_id = $user->id)";

But i receive a SQL syntax error because it seems that WHERE NOT EXISTS can't be used with INSERT. I've also tried a unique index in the DB but this is not an option.

5
  • 1
    Little Bobby says you may be at risk for SQL Injection Attacks. Learn about Prepared Statements with parameterized queries. Commented Aug 27, 2020 at 15:03
  • 1
    Doing a completely separate query to see if it exists first would work. Commented Aug 27, 2020 at 15:04
  • 3
    Why is a unique index not an option? This is the accepted (and really, the only effective) mechanism for doing what you're trying to do. Commented Aug 27, 2020 at 15:05
  • You can not guarantee duplicate prevention by doing a select first. Commented Aug 27, 2020 at 15:12
  • @GrumpyCrouton Any chance you can provide an example of how to do this? The first one would be a select, but then how would I use that? Commented Aug 28, 2020 at 14:54

1 Answer 1

1

In order to use a WHERE clause, you have to use a SELECT query for the data, not VALUES.

$sql = "INSERT INTO contact_sync_status (ghl_contact_email, ghl_contact_data, result, wp_user_id)
        SELECT '$source->email', '$payload', 'success', $user->id
        FROM DUAL
        WHERE NOT EXISTS (SELECT 1 FROM contact_sync_status WHERE ghl_contact_email = '$source->email' AND wp_user_id = $user->id)";

But it would definitely be better to add a unique index on (ghl_contact_email, wp_user_id) and then use INSERT IGNORE.

Sign up to request clarification or add additional context in comments.

3 Comments

Now present that as a prepared statement :D
I don't feel like doing that every time I answer a SQL question. As far as I'm concerned, the comment above is sufficient.
I agree, I was jesting more than being serious. I had to actually think about how to do placeholders correctly with that kind of query above, began to self-doubt myself, ran some tests, feel better now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.