Results 1 to 2 of 2

Thread: Prevent multiple INSERTS due to click event

  1. #1
    Join Date
    Apr 2012

    Prevent multiple INSERTS due to click event

    I have a div contained in an object that registers for a click event, and once clicked, uses ajax to communicate with the server and update a user rating for an item.

    When updating the rating, it checks if the item already exists in the database, if not, I use an INSERT, otherwise I use an UPDATE. My issue is that if the user clicks very quickly, two INSERTS are run and i end up with duplicates in my database. If the ajax call has a chance to return between clicks then it works as expected with an UPDATE being run on all subsequent clicks. Is there a standard means of preventing this or disabling the onclick and re-enabling it on the ajax call back?

    Here is my abbreviated code:

    PHP Code:
    $sql="UPDATE database SET rating=" $_POST['rating'] . ", status=" $_POST['status'] . " WHERE user=" $_POST['user'] . " AND isbn=" $_POST['isbn'];

    $result mysql_query($sql);       
        if (
    mysql_affected_rows()==0) {
    $sql="INSERT INTO database (user, isbn, rating, status) VALUES (" $_POST['user'] . ", " $_POST['isbn'] . ", " $_POST['rating'] . ", " $_POST['status'] . ")";
                if (!
    "------Book failed to add------");
    "------Book successfully added------");
    "------Book successfully updated------");
    //add event listener
    star1.addEventListener('click', function(e){changeYouStars(e, mySelf);}, false);

  2. #2
    Join Date
    Aug 2004
    One way to approach it would be to set a unique index on that DB table across whatever columns would define a uniquely identifiable row (maybe `user` and `isbn`?). Then you could always do an insert, but add an ON DUPLICATE KEY UPDATE clause to the query.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center