I have a form page in which either an INSERT or an UPDATE query is submitted, depending on the presence/absence of an ID (and when there's an ID it's used to retrieve the record and pre-populate the form). In either case, the processing is in form.php so the form's action is itself (action="/form.php">
). My problem is that when form.php reloads post-submit, the URL has an empty ID so the page enters 'INSERT' mode, rather than 'UPDATE' mode. What's the best practice way to resolve this?
What operator/condition should I add to this 'if' ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
... to include post-submit empty ID URL (i.e., form.php?ID=
)
OR,
How do I pass `$newID = mysql_insert_id();1 to the form's action? (I've tried a number of variations here w/out success)
$newID = mysql_insert_id();
... [ snip ] ...
<form method="post" action="/html/form.php?ID=<?php echo $newID; ?>">
I'm reading about hidden inputs and sessions but it's not yet clear to me how to use either to solve this problem. Lastly, since it isn't absolutely necessary that I reload the form page, I'm increasingly tempted to move the form processing/db queries to another page (e.g., process.php) to hopefully simplify; any opinions on this? What's best/common practice?
Many thanks in advance,
svs
Common practice should be to keep data posting separate from data displaying. This prevents accidental adds on a user's first arrival to the page as well as accidental double-posts if the user hits refresh.
In addition, keeping the logic separate makes the code more readable and maintainable in the future.
The approach you should probably look for is:
view.php?ID=<record to view> // Only displays a record already in the DB
add.php // The add record form with action="process_add.php"
process_add.php?Field1=<>&Field2=<>... // Receives data from add.php, puts it in
// the database and then forwards back to
// view.php or add.php as you see fit.
EDIT: While I have GET arguments on process_add.php, they are only there to demonstrate that they are being passed. They should be sent as POST arguments in and actual implementation.