0

How do I save the following form?

<form name="myform">
<input type="text" name="title" value="title" />

$result = mysql_query("SELECT id, text from details where parent='$parent' 
order by id asc") or die('Error');
while(list($id,$ftext) = mysql_fetch_row($result)) {
?>
<textarea name="formfield<?php echo $id;?>" id="<?php echo $id;?>">
<?php echo $ftext;?>
</textarea>
<?php
}
</form>

As you can see above, the MySQL query will load data and dynamically create textareas:

<textarea name="formfield34" id="34">text</textarea>
<textarea name="formfield56" id="56">more text</textarea>        
<textarea name="formfield78" id="78">anothet text</textarea>   

I need to update database like this:

$result = mysql_query("UPDATE details SET text='$formfield34' WHERE id ='34'") or die('Error');
$result = mysql_query("UPDATE details SET text='$formfield56' WHERE id ='56'") or die('Error');
$result = mysql_query("UPDATE details SET text='$formfield78' WHERE id ='78'") or die('Error');

The problem is that each form will have a different number of textareas loaded dynamically and different $ids. I can not imagine hot to save this form.

Thanks.

1
  • You could use foreach to step through $_POST to find fields called formfieldxx, and use a little text processing to write the content of formfieldxx to the database where id=xx. Commented Apr 29, 2013 at 19:55

2 Answers 2

3

What you probably need to do is to look at using array notation in your form field names like this:

<textarea name="formfield[34]" id="34">text</textarea>
<textarea name="formfield[56]" id="56">more text</textarea>        
<textarea name="formfield[78]" id="78">anothet text</textarea>

PHP will automatically build an array in $_POST['formfield']. that you can access with all this data. This make it easy to loop through this array and generate SQL for your updates.

foreach($_POST['formfield'] as $key => $value) {
    // write SQL here
}

Now, rather than a bunch of individual SQL queries, you might want to consider using REPLACE syntax so that you can insert/update your data with a single query.

Sign up to request clarification or add additional context in comments.

Comments

0

in the "while" while creating the textarea save an array with the id of these textarea.

Then retrace the array to use ids when you need it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.