How do you use INSERT INTO On Duplicate Key UPDATE
for form input? All the examples I've found online are with counters or predetermined values.
I've been able to get my code to work (thanks to some really helpful members) with the standard UPDATE
and SET
method, but my tables really call for using INSERT INTO On Duplicate Key UPDATE
.
'user_id'
is unique primary key in all of the tables and is a foreign key in all but the account table.
<?php
session_start();
require_once('config.php');
require_once('open_db.php');
$setlist='';
foreach ($_POST as $key=>$value) {
$setlist.=$key .'=\''.$value.'\',';
}
$setlist=substr($setlist, 0, -1);
$user_id=$_SESSION['SESS_USER_ID'];
$sql='UPDATE style_test SET '.$setlist.' WHERE user_id='.$user_id;
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
?>
The code that I was using previously to automatically INSERT every field is:
$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
$fieldlist.=$key.',';
$vallist.='\''.urlencode($value).'\',';
}
$fieldlist=substr($fieldlist, 0, -1);
$vallist=substr($vallist, 0, -1);
$user_id=$_SESSION['SESS_USER_ID'];
$fieldlist.=', user_id';
$vallist.=','.$user_id;
$qry='INSERT INTO style_test1 ('.$fieldlist.') VALUES ('.$vallist.')';