views:

144

answers:

3

Dear All, 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

A: 

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.

Sarfraz
A: 
  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
Martijn
A: 

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

RageZ
Ok! well, I do have an id which I am passing. Question is how to tell the "submit" button to produce different behaviours.
Giuseppe
you don't have to tell if there is no id or it is egal to 0 it means it is an update
RageZ