I have 2 arrays.
The first array has the table names for a simple DB in text.
The second array has the values of each table.
When I launch my form the field value send from form and has the equal value of tables array, take the value send from the form.
The Script :
<?php
if($_POST[send]=="ok") {
/// The structure it´s that and fixed , in the array_1 and 2 ///
$tables="name,phone,alias";
$values="Jhon,55543232,johny25";
/// Explode values in each case ///
$exp_tables=explode(",",$tables);
$exp_values=explode(",",$values);
/// Array for get values for each field ///
$i=0;
foreach($exp_tables as $exp_table) { ${$exp_table}[]="".$exp_values[$i].""; $i++; }
/// Bucle for get the result if vars send by form equal to the other vars and change by new value send form the form ///
foreach($exp_tables as $table) {
foreach($_POST as $key=>$value) {
if($table=="".$key."")
{
print "".$_POST[$table]."";
}
else { print "".${$table}{0}."";}
}
}
}
?>
The html form
<form action="" method="post">
<input type="text" name="name" value="" />
<input type="submit" name="submit2" value"send" />
<input type="hidden" name="send" value="ok" />
</form>
In the form I have "name" in the first field and in the array tables I have one field also called name.
When I send the form I must get this:
Jhon(change value by the value from the form),55543232,johny25
The Problem it´s repeat all time values and no get the results ok.
My question is: How can I fix this for put the values I send from form and change when the other values has the same name as in the array tables, but no works very well.
First of all, your variables $tables an $values are no arrays but strings.
An array looks like
array(value, value, value)
or
array( key=> value, key=> value, key value)
In your case you could use
$tables=array('name','phone','alias');
$values=array('Jhon','55543232','johny25');
//or, to make even simpler
$values=array('name'=>'Jhon','phone'=>'55543232','alias'=>'johny25');
Then, if you only want to output the name and check if the name is different from that in the array, you simply do:
if($_POST['name']==$values['name']){
print "".$_POST['name']."";
}
else{
print "".$values['name']."";
}
Related
I have a textbox within a HTML form. I'm trying to get PHP to add the value of that textbox to a PHP array as a key with a value of something else (for example, the word "bob"). The array should be persistent, it shouldnt be overwritten with new values each time, rather as the button is clicked further values should be added to the array.
My HTML form looks like this:
<form action="" method="post">
<textarea id="dl-textarea" name="dl-textarea" rows="4" cols="50"></textarea>
<input type="submit" value="Add to array" name="submitText"/>
</form>
And the PHP I currently have is:
<?php
session_start();
if (isset($_POST["dl-textarea"])) {
if ($_SESSION["array"] != ""){
$_SESSION["array"] .= ",";
}
$_SESSION["array"] .= $_POST["dl-textarea"];
} else {
$_SESSION["array"] = "";
}
$demo = $_SESSION["array"] == "" ? "gg" : $_SESSION["array"];
print_r($demo);
Which I picked up from the following StackOverflow answer.
How to create add value to array everytime i click submit button? in php (with session)
This inserts new values into the array with conventional keys (0, 1, 2, and so on). However, I would like to have some control over the keys so as to have the contents of the textarea as my key, and another value as my data (for example, if the textarea contained the word "text1", then when I click my button it would insert this into the array with "text1" being the key and something else as the data. And then afterwards, if the text area contained the word "text2", then clicking the button would add that to the array. So a final array might look like: ['text1':'bob','text2':'bob','text3':bob'])
Ive started working on a dynamic form script that allows a user to add form elements via Jquery, which is then in turn submitted to a PHP script.
I'm just after some feedback on ways to achieve this. At the moment I have the following:
When a user adds a form element the element is added with the following name array:
<textarea name="element[text][123]">
<input type="text" name="element[input][456]" />
As I need to know the type of form element that was submitted I am using a multidimensional array called 'element[][]' where the first level of the array is the type of element and the second element of the array is a unique ID and the value.
When I var_dump() This after submission PHP outputs:
array
text => array
123 => string 'The textarea value'
input => array
456 => string 'The input field value'
Im working on the PHP side of the script now and just wondering if there is a better way to do this.
Any thoughts?
UPDATE
I have to change the way that Im doing this as the array keynames are not unique.
If the user adds two textareas
<textarea name="element[text][123]">
<textarea name="element[text][456]">
When the user adds a form element, the element can be dragged so the positioning can be changed after the element was created. This allows a user to add an element but then move it to where they want it to appear.
PHP handles this ordering fine and accepts the array in the order that the form is submitted, however as mentioned above if the key names are the same then the order will be broken.
On the PHP side I need to know
the type of form field
the value of the form field
the unique ID, which is just a timestamp, of the form field
I think I might need to do what Cole mentioned, assigning the names as:
element[text_123]
I can then explode the keyname on '_' to determine the type and the identifier.
UPDATE
I took the script Jack posted and slightly modified it
$vars = $_POST['element'];
foreach ($vars as $id => $vals)
{
// $vars[id] outputs the ID number
// $vars[vals] is the array containing the type and value
echo "This fields ID is $id. ";
foreach($vals as $key => $value)
{
echo "Type was: $key and the value was: $value <br />";
}
}
A quick test of this outputted
This fields ID is 1338261825063. Type was: heading and the value was: xzczxczxczxczxczxc
This fields ID is 1338261822312. Type was: heading and the value was: asdasdasdasdad
From this I know the identifier and the array that it belongs to, the type and the value, but I also know the order that the data was submitted.
From that I can wrap my data in markup, perform any additional operations and then insert the data into the database.
Looks okay; you could also consider something like this (it introduces more fields though, so you must really think the benefit is worth it):
<input type="hidden" name="element[123][type]" value="text" />
<input type="hidden" name="element[456][type]" value="input" />
<textarea name="element[123][value]">
<input type="text" name="element[456][value]" />
Then you can do this:
foreach ($_POST['element'] as $name => $info) {
// $info['type'] is 'text' or 'input'
// $info['value'] is the user input
}
This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}
I have a form with multiple textboxes which are created dynamically, now all these textboxes are of same name lets say txt, now is there any way that when form processing happens we could read all the text boxes values using $_POST method, which are of so called same name. If possible how?
You have to name your textboxes txt[] so PHP creates a numerically indexed array for you:
<?php
// $_POST['txt'][0] will be your first textbox
// $_POST['txt'][1] will be your second textbox
// etc.
var_dump( $_POST['txt'] );
// or
foreach ( $_POST['txt'] as $key => $value )
{
echo 'Textbox #'.htmlentities($key).' has this value: ';
echo htmlentities($value);
}
?>
Otherwise the last textbox' value will overwrite all other values!
You could also create associative arrays:
<input type="text" name="txt[numberOne]" />
<input type="text" name="txt[numberTwo]" />
<!-- etc -->
But then you have to take care of the names yourself instead of letting PHP doing it.
Create your text box with names txt[]
<input type='text' name='txt[]'>
And in PHP read them as
$alTxt= $_POST['txt'];
$N = count($alTxt);
for($i=0; $i < $N; $i++)
{
echo($alTxt[$i]);
}
If you want name, you could name the input with txt[name1], then you could get it value from $_POST['txt']['name1']. $_POST['txt'] will be an associative array.
I put a variable (price) to a html form from database.
then user changes the price and submit the form and variable is updated in database.
I want to keep previous value (last state and show it in the form) but if I update the form variable keeps updating.
What is best way to remember previous value of variable (in array for example) ?
If you're updating this data in an actual Database, you should create a parallel table that holds the value of the previous row.
Otherwise, if you're updating only an array, you can just create a copy prior to updating the array: http://codepad.org/SvlasJ7f
<?php
$array = array('Old Value');
$lastarray = '';
updateArray($array,'New Value');
function updateArray(&$a,$v) {
$GLOBALS[lastarray] = $a;
$a = array($v);
}
?>
If you want to retain the LAST value AND display it on the screen, combine the two! Just display the previous value, in a readonly input field in your form. That way, you will still have the previous value every time the form is submitted.
<form action="process.php" method="POST">
<input type="text" name="Current" value="...">
<input type="text" name="Last" value="..." readonly="readonly">
</form>
Or am I missing something?