Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a table postviews which has columns post_id and ipaddress . I use a INSERT statement for this table on posts page whenever a post is opened, id of that post and IP address of viewer are sent to database and saved in their respective columns.

PHP
$stmt =$db->prepare("INSERT INTO postviews (post_id,IPaddress) VALUES (:post_id,:IPaddress)");


Now whenever one user opens same post again and again new rows are inserted with same post id and IP address which I want to prevent. So now I have added a third column counter to this table, so now whenever one user opens same post again and again instead of inserting new rows with same post id and IP address I would rather like to increase my counter column. I am not sure how to do it. Will something like this work:
PHP
$stmt =$db->prepare("INSERT INTO postviews (post_id,IPaddress) VALUES (:post_id,:IPaddress)
ON DUPLICATE KEY UPDATE counter = counter + 1");


I want to prevent creating new row only when both columns (post id and IP address) are same , but a new row should be created if any one of them is different than previous row, so unique composite key couldn't be used here.
Posted
Comments
PIEBALDconsult 15-Nov-15 9:06am    
I don't see why you would bother with the count. What use is it?
Gizmo3 16-Nov-15 6:07am    
thanks its solved, was building a post views system

1 solution

To solve this problem, you need to check whether a record exists or not. If the record (with same post_id and IPaddress) exists, then use the "UPDATE table" command to update the record, otherwise, use the "INSERT INTO table" command to insert a new record in the database.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900