Question: I'm parsing a json feed routinely and need to insert only the newest users from the feed and ignore existing users.

I think what I need is `ON DUPLICATE KEY UPDATE` or `INSERT IGNORE` based on some searching but I'm not quite sure which is why I'm asking - so for example:

```
users
1     John
2     Bob

```

Partial JSON:

```
{ userid:1, name:'John' },
{ userid:2, name:'Bob' },
{ userid:3, name:'Jeff' }

```

From this feed I only want to insert Jeff. I could do a simple loop through all users and do a simple SELECT query and see if the user id is already in the table, if not I do an INSERT, however I suspect it won't be an efficient and practical method. 

By the way, I'm using Zend\_Db for the database interaction if anyone would like to cater a specific answer :) I don't mind a generic strategic solution though.

Answer: 
You need to define userid as a PRIMARY or UNIQUE key and use something like:

```
INSERT IGNORE INTO table (userid, name) VALUES (2, 'Bob');

```

If the userid 2 already exists it will ignore and move on to the next insert.

You can also use ON DUPLICATE KEY UPDATE on your table schema. **One other alternative might be to use the REPLACE INTO syntax.**

```
REPLACE INTO table (userid, name) VALUES (2, 'Bob');

```

**This will try to INSERT, if the record already exists it will DELETE it before INSERTing it again.**
In the loop, you can do a update first, if no row affected, means it's a new entry. Keep track of those 'failed updates' then do an insert of them as new entries.

I'm not familiar with Zend\_Db but I assume it can return whether a update affected how many row(s).