简体   繁体   中英

php forms submit button

I am relatively new to php. I have the following problem. Suppose I have a page with

  • a form with two fields x, y and two buttons: submit and clear;
  • a table that shows the db records for x, y with two buttons, edit and delete

when I enter values in the form fields and press button, submit inserts the data in the db; data is then shown in the table below;

when I press edit on the table, the form is populated with the data from the selected record. Now I want submit to update the record and not just insert a new one.

How should I proceed?

Thanks!!!

Giuseppe

you should add some hidden field in your form to differentiate the updates and insert.

A good way to do that is for example to put your primary key has field

<input name="id" type="hidden" value="<?= $row['id']"/>

after on the PHP code you can do something like this

if(isset($_POST['id']) && $_POST['id'] != 0){
 // this is an update 
 $sql = "UPDATE ...."
 ...
} else {
 $sql = "INSERt ...";
 ...
}

for the insert form just don't put the hidden input or make the value being 0

First of you should be storing id of the current edit somewhere like hidden field or query string, once you have done that, you should use the update statement to update the record rather than inserting new one something like:

// sql query
update tablename set fieldname = 'fieldvalue'......... and son

You need to show your code for getting accurate answer.

  1. Add an identifier to your rows: an ID column in the database (preferably an UNSIGNED INTEGER), which is also in the table (you can use it as a querystring in the url you use for editing an entry), and as a hidden input in the form
  2. If you're adding an entry, make sure the hidden input is set to null, or zero (or some other value that cannot be a valid identifier)
  3. Whenever the form is submitted, test for the identifier to be null or something else
  4. If the identifier is null, add like you did before
  5. If the identifier is not null, update the element with the identifier from the input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM