How to use SQL - INSERT...ON DUPLICATE KEY UPDATE?

Posted by Probocop on Stack Overflow See other posts from Stack Overflow or by Probocop
Published on 2010-04-27T10:15:27Z Indexed on 2010/04/27 10:23 UTC
Read the original article Hit count: 214

Filed under:
|

Hi, I have a script which captures tweets and puts them into a database. I will be running the script on a cronjob and then displaying the tweets on my site from the database to prevent hitting the limit on the twitter API.

So I don't want to have duplicate tweets in my database, I understand I can use 'INSERT...ON DUPLICATE KEY UPDATE' to achieve this, but I don't quite understand how to use it.

My database structure is as follows.

Table - Hash id (auto_increment) tweet user user_url

And currently my SQL to insert is as follows:

$tweet = $clean_content[0];
$user_url = $clean_uri[0];
$user = $clean_name[0];

$query='INSERT INTO hash (tweet, user, user_url) VALUES ("'.$tweet.'", "'.$user.'", "'.$user_url.'")';
mysql_query($query);

How would I correctly use 'INSERT...ON DUPLICATE KEY UPDATE' to insert only if it doesn't exist, and update if it does?

Thanks

© Stack Overflow or respective owner

Related posts about sql

Related posts about mysql