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>";
}
?>开发者_如何学Go
You should use the MySQL ON DUPLICATE KEY clause:
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Also see REPLACE:
http://dev.mysql.com/doc/refman/5.0/en/replace.html
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.
精彩评论