If already Inserted then Update record


I have a products database driven website that I am building in dreamweaver, where I am inserting data into and I would like to set it so that if a record with this ‘code’ has already been inserted then it will update the particular record. I have this code so far which inserts the data into a table so far and am not sure what I need to add to this code to get the record to update if it has already been inserted into the table:

if ((isset($_POST[“MM_insert”])) && ($_POST[“MM_insert”] == “form3”)) {

$insertSQL = sprintf(“INSERT INTO ProductsUpdated (Code, Web_Price, Overriden) VALUES (%s, %s, %s);”,
GetSQLValueString($_POST[‘Code’], “text”),
GetSQLValueString($_POST[‘Web_Price’], “double”),
GetSQLValueString($_POST[‘Overriden’], “int”));

Any help would be much appreciated.


That’s an easy one…

First, you have the “code”, so the update would be in general terms:
Update table item="",item2="" where product=code…
But, if nothing to update, you would have to insert in general terms:
insert table (item, item2) values ("", “”)…

Here is a sample, loosely based on your insert sql you posted:


$query = “UPDATE ProductsUpdated SET Web_Price=’” . $_POST[‘Web_Price’] . “’, Overriden=’” . $_POST[‘Overriden’] . “’ WHERE Code = '” . $_POST[‘Code’] . “’”;
$result = mysql_query ( $query ) or mysql_error();

// Check if -UPDATE- worked, if failed use -INSERT-
if(mysql_affected_rows()==0) {
$query = “INSERT INTO ProductsUpdated (Code, Web_Price, Overriden) VALUES (’” . $_POST[‘Code’] . “’, '” . $_POST[‘Web_Price’] . “, '” . $_POST[‘Overriden’] . “’)”;
$result = mysql_query ( $query ) or mysql_error();


Basically both store data, the update does not need “Code” to be updated, just the others and uses “Code” in the WHERE to select that record. The INSERT needs to insert ALL the data. Hope that makes sense!
Good luck…