简体   繁体   中英

Update a row if ID exists else Insert

This is the code of a .php file. The column "memberid" has a unique index. When a user enters a record with an existing memberid, the record must get updated else a new row is created.

I also want to show an alert box. For test purposes I added like the way below, but it is not firing. No message is displayed.

I also want to know whether it is the right approach to handle insert/update automatically?

<META http-equiv="refresh" content="2; URL=socialprofile.html">
<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once("../Lib/dbaccess.php");

    //Retrieve values from Input Form
    $CandidateID = $_POST["inCandidate"];
    $SocialProfile = $_POST["inActivities"];

    $InsertQuery = "INSERT INTO candidate_db_social (memberid, socialactivities, lastupdated) VALUES (".$CandidateID.",'".$SocialProfile."',now())";
    $UpdateQuery = "UPDATE candidate_db_social SET socialactivities='".$SocialProfile."', lastupdated=now() WHERE memberid=".$CandidateID;
    try
    {
        $Result = dbaccess::InsertRecord($InsertQuery); 
    }
    catch(exception $ex)
    {
        $Result = dbaccess::InsertRecord($UpdateQuery);
        echo "<script type='text/javascript'>alert('".$ex."');</script>";
    }
?>

See the MySQL REPLACE keyword . It works exactly like INSERT , but overwrites existing records based on primary key. Read up on the details though, because it's not exactly equivalent to trying an INSERT, followed by an UPDATE.

INSERT ... ON DUPLICATE might be what you need instead. Situations with triggers or foreign keys come to mind. Longer syntax however :)

REPLACE INTO candidate_db_social (memberid, socialactivities, lastupdated) VALUES (".$CandidateID.",'".$SocialProfile."',now())";

you can use the INSERT ... ON DUPLICATE KEY UPDATE syntax, as in:

insert into t values ('a', 'b', 'c') on duplicate key
  update a='a', b='b', c='c'

use mysql

INSERT INTO table VALUES() 
                       ON duplicate KEY UPDATE ..; 

example :

http://www.mysqlperformanceblog.com/2006/05/29/insert-on-duplicate-key-update-and-summary-counters/

I usually just check for the existence of a record ID value from either the $_POST or $_GET array (depending on the situation). If a value exists and is numeric, attempt to UPDATE the row with the corresponding ID; if not perform an INSERT query.

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