3

I need to be able to only insert a row if the data doesn't already exist, except for the date column, which would always be different, so it will always insert a new row even though it shouldn't.

my code:

$postID = $_POST['postID']; //example, 817
$userID = logged_in(); //example, 2
$date = time();

mysql_query("INSERT IGNORE INTO likes SET userID='$userID', postID='$postID', date='$date'");

I would like to be able to do something like:

mysql_query("INSERT IGNORE date INTO likes SET userID='$userID', postID='$postID', date='$date'");

1 Answer 1

3

If you have a UNIQUE constraint on userID and postID you can do whatever you're doing now, the date column would not get updated if there's already a record.

If you want to have the date column updated if the record does exist (for that particular user and post) you can use ON DUPLICATE KEY UPDATE date = '$date'.

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

2 Comments

I would suggest you check the docs and also make sure you don't already have existing indexes, but this should do it: ALTER TABLE LIKES ADD UNIQUE(userID, postID);
Ohh, now I understand what you meant by the unique constraints, I never even thought about doing it this way, thanks. I'll have to be using this more often.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.