简体   繁体   中英

Insert record if user_id is unique in table, if not update column

I need to INSERT record if user_id is unique in table map , but if not then UPDATE that row where user_id=:user_id with data...

What I try:

  try {

      $result = $db->prepare('SELECT user_id FROM map WHERE user_id=:user_id');
      $result->bindParam(':user_id', $user_id); 
      $result->execute();

    //echo $jsonTable;
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
           try {   
               if ($result==null) {
               $STH = $db->prepare("INSERT INTO map (json, user_id) VALUES (:json, :user_id)");

                $STH->bindParam(':json', $_POST['mapData']);
                $STH->bindParam(':user_id', $user_id);
                $STH->execute();
               } else {
                $STH = $db->prepare("UPDATE map SET json = :json WHERE user_id= :user_id");

                $STH->bindParam(':json', $_POST['mapData']);
                $STH->bindParam(':user_id', $user_id);
                $STH->execute(); 
               }
            } catch (PDOException $e) {
                echo $e->getMessage();
            }
            echo "<p>Data submitted successfully</p>";

        }

So here I try to check is user_id I need to add exist into table, and if there is no user_id, so if prepared user_id is new then I try to insert data, but if user_id alredy excist into table then to UPDATE that record...

But this dont work for me, also dont give me any error?

I'beginer to php, so sorry about trivial question... Thanks!

UPDATE: I also try to insert but if user_id is duplicate then to UPDATE:

        try {        
         $STH = $db->prepare("INSERT INTO map (user_id, json) VALUES (:user_id,:json)
on duplicate key update json=values(json)");


                $STH->bindParam(':json', $_POST['mapData']);
                $STH->bindParam(':user_id', $user_id);

                $STH->execute();

            } catch (PDOException $e) {
                echo $e->getMessage();
            }
            echo "<p>Data submitted successfully</p>";
    }

To check uniqueness you can use an unique key to have uniqueness checked by the db: http://dev.mysql.com/doc/refman/5.6/en/mysql-indexes.html

Or better, ususally ids are primary keys of the table, this means you don't need to worry about uniqueness, primary key is always unique and the db checks it for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM