www.webdeveloper.com
Results 1 to 2 of 2

Thread: Prevent multiple INSERTS due to click event

Hybrid View

  1. #1
    Join Date
    Apr 2012
    Posts
    11

    Prevent multiple INSERTS due to click event

    Hello,
    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 (!
    mysql_query($sql$connection))
            {
                echo(
    "------Book failed to add------");
            }
            else
            {
                echo(
    "------Book successfully added------");
            }
        }
        else
        {
            echo(
    "------Book successfully updated------");
        } 
    Code:
    //add event listener
    star1.addEventListener('click', function(e){changeYouStars(e, mySelf);}, false);

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,222
    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.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

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



Recent Articles