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
REPLACEkeyword. It works exactly likeINSERT, 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 🙂