I have form.php in which a record is either created or edited. This page is called either by a a 'New Record' link, in which case there's no ID set, or by an 'EDIT' link in which case $_GET['ID'] is set (and used to retrieve the record).
Plan A was: Submitting form.php to process.php; in process.php, if there's an ID, the query is an UPDATE, otherwise it's an INSERT. At one point this if/else was working as intended but refreshing created dupes so I began playing with 'ON DUPLICATE KEY UPDATE', however w/out success. Plan B eventually occurred to my tiny little brain: shouldn't process.php have only an INSERT query, with ON DUPLICATE KEY UPDATE added? Haven't got this working yet either.
process.php:
<?php
// get $_POST from form.php *** note: no ID if it's a New Record ***
$id = $_POST['ID'];
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
$client = $_POST['client'];
$issueDate = $_POST['issue-date'];
$task = $_POST['task'];
$subTotal = $_POST['sub-total'];
$tax = $_POST['tax'];
$invTotal = $_POST['invoice-total'];
$datePaid1 = $_POST['payment-date-1'];
$datePaid2 = $_POST['payment-date-2'];
$comments = $_POST['comments'];
if (isset($_POST['submit'])) {
$query = "INSERT INTO $table SET
invNumber = '$invNumber',
invDate = '$invDate',
projNumber = '$projNumber',
client = '$client',
task = '$task',
issueDate = '$issueDate',
subTotal = '$subTotal',
tax = '$tax',
invTotal = '$invTotal',
datePaid1 = '$datePaid1',
datePaid2 = '$datePaid2',
comments = '$comments'
ON DUPLICATE KEY UPDATE
invNumber = $invNumber,
invDate = $invDate,
projNumber = $projNumber,
client = $client,
task = $task,
issueDate = $issueDate,
subTotal = $subTotal,
tax = $tax,
invTotal = $invTotal,
datePaid1 = $datePaid1,
datePaid2 = $datePaid2
ID = LAST_INSERT_ID(ID)
";
$lastID = mysql_insert_id();
$result = mysql_query($query) or die(mysql_error());
$affRows = mysql_affected_rows();
if (($result) && ($affRows)) {
echo "<p class=\"status\">
<strong>RECORD #".$id." UPDATED.</strong><br />
<strong>Records updated: " . $affRows . "</strong>
</p>";
} // END if ($result ...
} // END CASE 1
?>
Refreshing process.php INSERTs dupes whether there's an ID or not. My 'ID' column, btw, is primary key, unique index, auto-increment. So how does the $query check the ID before either INSERTing or UPDATEing?[enter pulling-hair-out cliché following days and nights of research and experimentation]
Thanks in advance, s
p.s. re: injection:
I've been including this chunk in my head.php - pls let me know if this covers injection:
<?php
// prevent SQL Injection in $_POST variables:
foreach ($_POST as $key => $value) {
$_POST[$key] = mysql_real_escape_string($value);
}
// prevent SQL Injection in $_GET variables:
foreach ($_GET as $key => $value) {
$_GET[$key] = mysql_real_escape_string($value);
}
?>