PHP Form Design Best Practices

I have been using PHP for some time, and I always wondered how to submit a single form for processing updates and inserting into the database. I am currently using two separate forms to do this, and they both have basically the same information and text fields, etc. I know there is a better way to handle this, but I'm not sure what it is.

I tried to use one form in the past, but the html mixed with php looks awful and it is very difficult to maintain. I am after the "clean" and neat.

Can someone please put me on the right track.

One of the things I should use is the POST values, if the user submits the form and the validation fails, the update should not destroy the values ​​already entered.

+7
php
source share
2 answers

You can use one form with a hidden field for id . If this field is set, then you must update the $_POST['id'] entry to the rest of the forms. If the field is not set (that is, it has value = ""), you must insert the form data in a new record.

You will set the id field according to the action, for example, /data/edit/1 set the id field to value , and / data / new`, will not set the value for it.

For example, your submission may be

 <form action="/data/edit/1"> <input type="hidden" value="<?php echo $data->id; ?>" /> <input type="text" value="<?php echo $data->name; ?>" /> </form> 

For a new entry, call up your view with the following data

 $data->id = ''; $data->name = ''; 

In the case of a known record, just run the $data object with the data

 $data->id = $record_id; $data->name = $record_name; 
+5
source share

This is how I will probably do it without using any other frameworks / libraries, etc. This is basically what Elazar Leibovitch said.

  <?php //id is zero or a record id depending on whether updating or inserting //an existing record could be edited using edit.php?id=10 //if the id GET parameter is omitted a new record will be created $id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0; $error = ''; if ($id) { //this array would be in the same format as the one below $record = fetchRecordFromDb($id); } else { $record = array( 'field1' => 'default value', 'field2' => 'some other default' ); } //allow POST data to override what is already in the form foreach ($record as $key => $value) { if (isset($_POST[$key])) { $record[$key] = $_POST[$key]; } } if (isset($_POST['submit'])) { if (!validateForm()) { $error = 'Some form error'; } else { if ($id) { updateRecord($id, $record); } else { insertRecord($record); } //ok, redirect somewhere else header('Location: http://somewhere'); exit(); } } ?> <form method="post"> <?php echo $error; ?> <input type="hidden" name="id" value="<?php echo $id; ?>"> <input type="text" name="field1" value="<?php echo htmlspecialchars($record['field1']); ?>"><br /> <input type="text" name="field2" value="<?php echo htmlspecialchars($record['field2']); ?>"><br /> <input type="submit" name="submit"> </form> 
+1
source share

All Articles