Cory
Cory

Reputation: 742

Replacing MySQL Records?

I'm working on a custom forum and trying to set up a table to keep track of what users viewed what threads.

The table is very simple. thread_id, user_id, thread_view_date.

Every time someone views a thread it will update the table with the thread_id, user_id and view date so the system knows if they viewed a thread or not.

The trouble I'm having is replacing records.

As of now it is just adding new records. So if a user was to view a thread 3 times, it would insert 3 records as apposed to updating the old record's view time.

I'm currently using this on the thread page

$viewed_sql = "
        REPLACE INTO forum_thread_views (
            thread_id,
            user_id,
            thread_view_date
        ) VALUES (
            '$thread_id',
            '$_SESSION[user_id]',
            '$date'
        )
    ";
$viewed_query = @mysqli_query ($db_connect, $viewed_sql);

What would be the easiest way to updating the thread_view_date if the user has already viewed the thread, and if not create a new record?

Thanks.

Upvotes: 0

Views: 60

Answers (1)

Vadym
Vadym

Reputation: 5284

First of all add unique key to "thread_id, user_id' pair.

ALTER TABLE forum_threads_views ADD UNIQUE KEY (thread_id, user_id)

Then rewrite your query to this one

INSERT INTO forum_thread_views (
        thread_id,
        user_id,
        thread_view_date
    ) VALUES (
        '$thread_id',
        '$_SESSION[user_id]',
        '$date'
    ) ON DUPLICATE KEY SET thread_view_date='$date'

Upvotes: 2

Related Questions