Dynamically added form elements - php

This question is basically for my understanding, so kindly guide me. I dont require any code but just the approach for solving this type of problem.
I am using jquery to dynamically add form elements. For example, I want user to enter his favourite movie. I have given him an add button to add more movies. Now if user adds 10 times for 10 movies, how will i save this data to database ? i mean i will have only one column for movie but user is entering 10 (some might add 100) so how is this data stored ?
I have asked this question to basically understands how to save data when the form elements are dynamically added ? shall i save them to column movies and seperate them by commas or something else ?

There are many approach to solve this problem. One solution to this is AJAX. say example you are using php
1) Sort form data with each use press button; jQuery Form.
2) a php function to process sql queries.
3) call php function in ajax in success method.
4) store value in database.

In the form elements that you add, you would make the name= value into an array, so that the various identical items could be processed.
For example, suppose you are cloning a table row. Suppose this is the template row that you are cloning:
<tr>
<td>
Movie Name: <input type="text" name="mov[]" />
</td>
</tr>
After the form was posted, the data would appear something like this:
POST DATA:
Array
(
[mov] => Array
(
[0] => (the initial, template row would have no value)
[1] => Gladiator (whatever user typed in)
[2] => Troy (the next movie entered by user...
The code I used to view the POST output above looks like this:
If (empty($_POST)===false) {
echo '<pre>';
echo 'POST DATA:<br />';
print_r($_POST);
echo '<br />*********************************************************<br /><br />';
echo 'UPLOADED FILES:<br />';
print_r($_FILES);
echo '</pre>';
die('Dying immed inside IF EMPTY($_POST)===FALSE...');
}

Related

How to let PHP add another line for every form

I'm using Javascript to create more form fields, to be more specific I'm using jQuery append() to create copies of form fields I already have when a button is pressed.
For example there is an exercise form field, then when someone presses the + button they get another form field to add a second exercise. Now I have to get all these exercises into a PHP file, with no limit so someone could add a 1000 exercises and they would all get sent to my PHP.
I have it setup so jQuery gives them all a name tag with exercisex, the 2nd x being the number of the form field, so the original is exercise1, the second one exercise2, etc.
Now I submit the form and it gets send to another file, submitted.php.
In this file I have it setup for the original form field like this:
$exercise1 = $_POST['exercise1'];
and to put it in an array
$arrExercise = array (
>"exercise1" => $exercise1 );
What I'm looking is for a way that PHP automatically adds this:
$exercise2 = $_POST['exercise2'];
$exercise3 = $_POST['exercise3'];
and adds to the array
"exercise2" => $exercise2
"exercise3" => $exercise3
etc. for all the numbers ofcourse
Now obviously I can't add a unlimited amount into this myself so I was wondering how to get PHP to add them automatically according to how many were added.
I see the obvious risk that someone could spam it by adding a million exercises but that's not a concern for the environment this will be used in.
I tried a for loop but got stuck eventually:
I don't remember the exact code but I tried to add a variable, lets call it n, this variable would get a +1 everytime I pressed the + button so if n=1 at the start, pressing the button once makes it 2, then 3, then 4 etc. and then I got stuck thinking I'd still need to add an infinite amount of
$exercise + n = $_POST['exercise' + n];
if that would even work anyways.
Thanks for any help in advance.
I just solved a similar issue yesterday - here's how.....
The 'key' is to get the form names setup before sending to PHP.
(as you didn't give examples of your form, I will use mine for example - easy enough to port over to your project)
In my project, the user is allowed to add custom menu (nav bar) items as well as links under it, etc.
The way I solved it was to name things where PHP would get a nicely formed array in the $_POST;
<input type="text" name="menu1[Name]" value="">
<input required type="text" name="menu1[data][1][text]" value="">
<input required type="text" name="menu1[data][1][link]" value="">
'rinse/repeat' for all the form values that get added (replacing the '1' in the name with your variable) - you would also replace all 'menu1' with your 'exerciseX'
Now, put a 'Submit' button on the page;
<button type="button" id="custommenusave">Save Changes</button>
A bit of jQuery makes simple work of it....
$("#custommenusave").click(function () {
update_custom_menus();
});
function update_custom_menus() {
var form = $("#form_custom_menus");
$.post("../data/ajax.php", 'function=set_custom_menu&' + form.serialize(), function (data) {
form.submit();
});
}
PHP gets a nice array to work with (I've done a json_encode to make it simpler to see....)
{"menu1":{"Name":"'my menu #1'","data":{"1":{"text":"first","link":"https:\/\/example.com","options":"tab"},"2":{"text":"the second link","link":"http:\/\/example2.com","options":"tab"}}},"menu2":{"Name":"'menu #2!!!!'","data":{"1":{"text":"link in menu #2","link":"https:\/\/example.com","options":"tab"}}}
Then, pull your user's answers and work with them (of course, you should clean any data that comes from a user - no matter how much you 'trust' them!)
This should give you an idea of at least one way (with working code) that you can go.
name of your input should be an array so you can add multiple inputs by same name
<input required type="text" name="exercise[]">
$count = 1;
$finalArray = array();
if(is_array($_POST) && count($_POST) > 0){
foreach ($_POST as $value) {
$finalArray['exercise'.$count] = $value;
$count++;
}
}
print_r($finalArray);

PHP POST all values from checkbox list

Dynamically created checkbox list then POST retrieval on another page.
First off, Thanks in advance.
A couple questions regarding best practices with the checkboxes in a form and then $_POST.
Family picture album stuff. I am getting an array back from my brothers database and putting it in a loop.
Question 1-
Is it best practices when wanting to retrieve this information on another page to have the "name" be the familyPictureID or should I put that in the "value"?
Sample of table element inside a loop:
<td data-label="Active">
<input class="checky" type="checkbox" name="cList[<?php echo $row['familyPictureID']; ?>]"
<?php if($row['active']==1) { echo 'value="1" CHECKED>';
} else { echo 'value="0">'; }
?>
</td>
Question 2-
When retrieving this information on a secondary page, how do I get all the values from the checkboxes? I want to know if they are checked or not but also pair that up with the 'familyPictureID'. Is that correct and best practices?
I am trying to get them like so:
if(!empty($_POST['cList'])) {
echo "check box test <pre>";
print_r($_POST['cList']);
echo "</pre>";
foreach($_POST['cList'] as $familyPictureID) {
echo "check=$familyPictureID<br>";
}
}
I would then send this back to my brothers database with an UPDATE to these family pictures whether they are checked or not.
Does this make sense?
Thanks in advance. I searched for something similar but people on here are doing some complicated stuff that seems way beyond the scope of what I am trying to do.
Thanks!
-MT
You can do it either way. If you put the ID in the name, then you can write:
foreach (array_keys($_POST['cList']) AS $id) {
echo "check=$id<br>";
}
If you put the ID in the value, you would write:
foreach ($_POST['cList'] AS $id) {
echo "check=$id<br>";
}
Only boxes that are checked get sent to the server, so both of these will iterate over the checked boxes.
If you have other input fields that are also arrays based on the ID, then for consistency I would recommend doing the same thing with the checkboxes.

i have a textbox which extract the content of dropdownlist now whenever i change the extracted content it should be saved into database

I have a text box which extracts the content of dropdownlist.Now whenever i extract the content i too need to edit it ana save it into the database.How can i do????
Here is my code:
<?php
require'conn.php';
$select_query="Select dynamictext from tbl_content where type=1";
$select_query_run =mysql_query($select_query);
echo'Dynamictext:';
echo "<select name='dynamic text' id='names' >";
while ($select_query_array= mysql_fetch_array($select_query_run) )
{
$value=$select_query_array["dynamictext"];
echo "<option value='$value' >".htmlspecialchars($select_query_array["dynamictext"])."</option>";
}
echo "</select>";
?>
Based on the clarification I got above from #krisha above, I'm going to take a stab at answering this. You'll want to refer to my comment above, for a definition of (Option A) and (Option B), as I defined them.
Let's assume you've got (Option A) working and that (as far as the select HTML element is concerned), it is functional.
Let's also assume that you know to do the following:
Place the select tag inside of a form tag.
Set the form tag's action and method values.
Place a <input type="submit" value="Submit"> inside of the form tag.
If none of the above made sense, see here.
Once you've done everything above, that will result in the value of the HTML drop-down being available to PHP after the user clicks the Submit button and the page refreshes. How the value of the drop-down is passed through the submit process will depend on the method value you pass to the form tag. I'll assume you use method="get" (which will result in the value of the drop-down appearing in the URL after the refresh). If you want more info on get versus post, see here.
Once the refresh occurs, you use PHP's $_GET[""] to retrieve the value of the HTML drop-down. In your case, you would use $_GET["dynamic text"] (since the name of your select is dynamic text). You could set this value to a variable, like so:
$value_of_select = $_GET["dynamic text"];
At this point, you have the value the user selected from the HTML drop-down. Now, push it to the database. It looks like you already understand how to pass queries to a database. The only difference in this case is that you want to do an insert or an update, not a select.

Website form populated from mySQL database, how to return data

I am trying to write a wordpress plugin and I have hit a bump. I am new to PHP (coded in Java before) and javascript so I am not sure whats the best way to solve my problem.
The Background
I have some data in a mySQL DB that I am using (each row has a unique ID and some other information I have added). I am able to search the DB using
$headss = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}costumesdb WHERE location = 'head'", ARRAY_A);
And display some of the information to the user using (this is one of 5 different drop-downs but they are all created in the same way)
Head: <select name="head">
<?php foreach ($heads as $head) { ?>
<option value="<?php echo $head['pieceName'] ?>"><?php echo $head['shopName'] . " - " . $head['pieceName'] ?></option>
<?php } ?>
</select>
For the moment I want the user to be restricted to choosing information that is already in the system.
The problem
The DB contains 2 pieces of information that the user does not need to know to fill in the form (a website URL and a picture URL). I need these 2 pieces of information once the form is submitted (I need to write some more code for that) to the server which spits out another page with the 2 URL's in it.
Whats the best way to send the data back to a PHP script? Am I able to access the row of data that the user has selected in the drop down and send the unique ID for that row back or do I need to do something else?
Edit:
This is the script that I am using to submit the code:
$('#createacostume').form({
success:function(data){
$.messager.alert('Info', data, 'info');
}
});
'
And then the page to display the information returned is:
$cname = $_POST['cname'];
$head = $_POST['head'];
echo "Data Returned Name $cname head $head
I think this is what you are asking:
User has to choose an item from a drop down and submit a form. You have to display the website URL and the image for that item in a second page. You want to know how this is typically accomplished.
If that's the case, you should pass the row id of the item to the second page like so:
<option value="<?php echo $head['ROW_ID'] ?>"><?php echo $head['shopName'] . " - " . $head['pieceName'] ?></option>
Then use the ROW_ID in the second page to access the data from the database and print out the website URL and the image.
Submit the first form (without the two field), INSERT the data into the database, get the ID of insert.
Pass the ID to the next page which would set the ID into a hidden form field (or GET or POST parameter, plenty of choices) of the new form (with the two fields and just UPDATE the database upon submitting the second form.
If you like to show the original data in the second form, just pull the data from the database and use it to render the form instead of passing just the ID into a hidden field.

Form reviewing in HTML

I hope I'm not posting a duplicate question but I've looked around (and googled as well!) and nothing has given me the answer I'm looking for.
I have a form in HTML. When the user submits the form the values get stored with mysql under their user account for the site.
The issue is, I'd like the user to be able to go back and edit the form any time they like.
I could certainly just populate the form with values from php when the users review the form, but it gets tricky when I try to populate a file input field (and the file has been saved in mysql using the blob type). Not to mention that I'd like to do this as cleanly as possible.
Ideally it would be nice if there was a convenient module for reviewing forms that have already been submitted in JQuery per se.
Can anyone offer any advice? Thanks in advance!
Edit:
Here's a good example of what I mean - in chrome if I fill out a form and redirect to the next page after hitting submit, if I hit back I come back to the form and it's still filled out with the information I entered previously! Could I invoke this behaviour whenever I want to, as opposed to only when the user hits back?
You can't pre-fil an <input type="file" . . but surely when they come back to the form, they want to see the file they've uploaded .. this is what you mean right ..
So if its a picture, you could just do: <img src="loadpic.php?id=$var" />
If it's files they've uploaded, just list the file name / date and other data.. etc in some sort of list.
Then you could still show the <input type="file"> .. but with the label, 'add more pictures' or 'add another file'. .etc
Unless someone has a better way, at the moment I'm using a combination of 2 things:
1) Utilizing the $_SESSION variable
2) Setting the "name" attribute of every input in the form to the name of the field it corresponds to in the database.
This way I can loop through all the values dynamically instead of hardcoding them all in. Some input types (like file) are exceptional and will be handled on their own. Other that I can do something like this:
To insert into mysql:
$fields = array();
$values = array();
foreach ($_POST as $field => $value) {
$fields[] = $field;
$values[] = addslashes($value);
}
$fieldString = 'Table_Name('.implode(', ', $aFields).')';
$valueString = "VALUES('".implode("', '", $aValues)."')";
mysql_query("INSERT INTO $fieldString $valueString");
Reviewing the form is somewhat similar. I am using javascript to hook into document.onload. I need to pass javascript the records from mysql so that it may populate the form. Then it's a simple matter of getting elements by their name and assigning them their values that were passed from php.
The easiest way to do it and not have to go back to the database would be to store the values in a session.
<?php $_SESSION['myvalue'] = $inputvalue; ?>
On the html form use:
<input type="text" name="myName" value="<?php echo $_SESSION['inputvalue']; ?>" />
When completed don't forget to unset the session variable:
<?php session_start(); unset($_SESSION['myvalue']); ?>

Categories