Detecting which form was submitted in php - php

What would be a reliable way to detect which form was submitted in a situation like below? All submit to the same page, which in turn does things based on which form was submitted. Many drawbacks have been pointed out to the way this is being done. To top it all, even querystrings go to the same script. How would you suggest this be done?
Form one has two input fields, form two has three.
<?php
if ( isset($_POST['valOne']) && isset($_POST['valTwo']) && isset($_POST['valThree']) ) {
echo 'This is form three';
} elseif ( isset($_POST['valOne']) && isset($_POST['valTwo']) ) {
echo 'This is form two';
} else {
echo 'Neither one or two';
}
$formOne = '<form method="post" action="http://localhost/dev/form.php">';
$formOne .= 'Name: <input type="text" name="valOne" value="Foo" autocomplete="off"><br>';
$formOne .= 'Description: <input type="text" name="valTwo" value="Bar" autocomplete="off"><br>';
$formOne .= '<input type="hidden" name="secretVal" value="secretKey">';
$formOne .= '<input value="Add This" type="submit">';
$formOne .= '</form>';
$formTwo = '<form method="post" action="http://localhost/dev/form.php">';
$formTwo .= 'Name: <input type="text" name="valOne" value="Foo" autocomplete="off"><br>';
$formTwo .= 'Description: <input type="text" name="valTwo" value="Bar" autocomplete="off"><br>';
$formTwo .= 'URL: <input type="text" name="valThree" value="Tar" autocomplete="off"><br>';
$formTwo .= '<input type="hidden" name="secretVal" value="secretKey">';
$formTwo .= '<input value="Add This" type="submit">';
$formTwo .= '</form>';
$formThree = '<a href="http://localhost/dev/form.php?do=getIt">This is GET. Get it?<a/>';
echo $formOne;
echo '<br>';
echo $formTwo;
echo '<br>';
echo $formThree;
?>

You could use a hidden input with different names for the 2 forms and on server side you can check with if(isset($_POST['hidden_for_form1'])) or if(isset($_POST['hidden_for_form2'])).

You could add a form_id parameter to the form action.
<form method='post' action='http://localhost/dev/form.php?form_id=1'>
Then in your code switch on $_GET["form_id"];

I'd use hidden inputs
<input type="hidden" name="form" value="form1">
Also on a side note, is there any reason you're storing the form code in a variable?

Add a hidden input:
<input type="hidden" name="form" value="one">
<?switch($_POST['form']){
case "one":
...
?>
You can also assign the name and value to a submit button, but that doesn't work if the user presses enter

You need to assign some name in submit, like:
<input type="submit" name="form1" value="Add This">
<input type="submit" name="form2" value="Add This">
<input type="submit" name="form3" value="Add This">
so..
if(isset($_POST['form1'])){ //do some stuff }
if(isset($_POST['form2'])){ //do some stuff }
if(isset($_POST['form3'])){ //do some stuff }

Related

Get checked or not checked multi value checkbox

Hi everyone I have a form with 5 checkboxes, once I run the post I would like to have all the checkboxes with the current status.
Example:
checkbox 1: on
checkbox 2: off
checbox 3: on
checkbox 4: off
checkbox 5: off
This is my code but it doesn't work with non-on states
<?php
if(isset($_POST['submit'])){
$array = $_POST["check_list"];
}
?>
<form action="" method="post">
<input type="checkbox" name="check_list[]"><label>Mon</label>
<input type="checkbox" name="check_list[]"><label>Tue</label>
<input type="checkbox" name="check_list[]"><label>Wed</label>
<input type="checkbox" name="check_list[]"><label>Thu</label>
<input type="checkbox" name="check_list[]"><label>Fri</label>
<input type="submit" name="submit" Value="Submit"/>
</form>
How can I get all the checkboxes with the statuses sent in the post?
Thank You
The value keyword can be used to specify the value:
Hardcoded Values
$days = ['mon', 'tue', 'wed', 'thu', 'fri'];
if(isset($_POST['submit'])){
$array = $_POST["check_list"];
foreach ($days as $day){
$isChecked = in_array($day, $array);
echo $day . ' is ' . ($isChecked ? ' checked' : ' not checked') . '<br />';
}
}
?>
<form action="" method="post">
<?php
foreach ($days as $day){
echo '<input type="checkbox" name="check_list[]" value="' .$day.'"><label>'.$day.'</label>';
}
?>
<input type="submit" name="submit" Value="Submit"/>
</form>
Dynamic Values
If the fields get added dynamically, hidden inputs can be used. The following snippet adds a hidden input for every available option. These hidden inputs can then be used to determine if there is an associated checkbox, and thus get the value.
Checkout the following example:
<?php
if(isset($_POST['submit'])){
$options = $_POST["check_list_options"];
$checkedValues = $_POST["check_list_values"];
foreach ($options as $optionId){
$isChecked = array_key_exists($optionId, $checkedValues);
if($isChecked){
echo 'option ' . $optionId . ' is checked and has value: '.$checkedValues[$optionId].'<br />';
}else{
echo 'option ' . $optionId . ' is not checked<br />';
}
}
}
?>
<form action="" id="checklist_form" method="post">
<div class="results">
</div>
<button type="button" id="add_days">
Add days
</button>
<input type="submit" name="submit" Value="Submit"/>
</form>
<script>
var addDays = document.querySelector('#add_days');
var form = document.querySelector('#checklist_form');
var results = document.querySelector('.results');
addDays.addEventListener('click', function(){
var inputId = document.querySelectorAll('.input').length;
results.innerHTML += '<input type="hidden" name="check_list_options[]" value="'+inputId+'" />' +
'<input type="checkbox" name="check_list_values['+inputId+']" value="mon'+inputId+'" class="input" />' +
'<label>Day '+inputId+'</label>' +
'<br />';
})
</script>
You can do this by giving a name to each checkbox or by adding the key to the name of checkbox, and create an array that contains the name of each checkbox, then check in a loop if the equivalent checkbox is set:
$checkboxes = ['checkbox 1', 'checkbox 2', 'checkbox 3', 'checkbox 4', 'checkbox 5'];
if(isset($_POST['submit'])){
foreach($checkboxes as $key=>$value) {
echo $value.': ';
if(isset($_POST["check_list"][$key])) echo 'on '; else echo 'off ';
}
}
?>
<form action="" method="post">
<input type="checkbox" name="check_list[0]"><label>Mon</label>
<input type="checkbox" name="check_list[1]"><label>Tue</label>
<input type="checkbox" name="check_list[2]"><label>Wed</label>
<input type="checkbox" name="check_list[3]"><label>Thu</label>
<input type="checkbox" name="check_list[4]"><label>Fri</label>
<input type="submit" name="submit" Value="Submit"/>
</form>

$_POST and code manipulation

I want to grab the value of a field using $_POST, manipulate it, then pass the value back to the same page to the same field before the PHP code manipulates it.
If I put the PHP code after the field, it manipulates the code, reloads the page but doesn't put the manipulated code back into the field.
if (!isset($input)) {
$input = '';
}
echo '<form id="testform" method="post" action="">';
echo '<input type="text" name="inputText" value="' . $input . '">';
echo '<button type="submit" name="button"> Button </button>';
echo '</form>';
$input = $_POST['inputText'];
if(isset($_POST['inputText'])) {
$input = $input . ' manipulated';
}
echo $input; //test
If I put the PHP code before the field, it can't find the field to manipulate the value...
if (!isset($input)) {
$input = '';
}
$input = $_POST['inputText'];
if(isset($_POST['inputText'])) {
$input = $input . ' manipulated';
}
echo $input; //test
echo '<form id="testform" method="post" action="">';
echo '<input type="text" name="inputText" value="' . $input . '">';
echo '<button type="submit" name="button"> Button </button>';
echo '</form>';
Obviously the first approach is more correct, but how do I pass the $input variable to the field before the rest of my PHP manipulation code executes?
I tried $_POST['inputText'] = $input as a desperate attempt but nothing..
Well, from what I've understood in your explanation, you want to change the input value to something else and show it in he same field. If that's correct, you may want to do this:
<form id="testform" method="post" action="">
<input type="text" name="inputText" value="<?php echo ( isset($_POST['inputText']) ) ? sprintf( '%s manipulated', $_POST['inputText'] ) : ''; ?>">
<button type="submit"> Send </button>
</form>
Let me know if that's what you wanted. Regards !
Try
$input = isset($_POST['inputText']) ?$_POST['inputText'] :'';
in the begining instead of
if (!isset($input)) {
$input = '';
}

when perfoming a multiple row updates, how do i access other form element values, apart from the checkbox?

i wrote a piece of code to do multiple row deletions based on ticked check boxes.
Now i need to mordify it to do multiple row updates.
i have been failing to access the textbox values for each row.
here's my code, in general.
<?php
if (isset($_POST["SaveComments"]) && isset($_POST["SaveEachComment"]))
{
while(list($key, $val) = each($_POST["SaveEachComment"]))
{
if($val == 'commentbox')
{
// do the update here. $val contains the ID
}
}
}
?>
<form id="form1" name="form1" method="post" action="test.php">
<input type="checkbox" <?php echo 'name="SaveEachComment['.$row["comment"].']" ';?> value="commentbox" id="commentbox" />
<input type="text" name="rowcomment" size="55" value="<?php echo $comment;?>" />
<input type="submit" name="SaveComments" value="submit" />
</form>
I just added a for loop to print multiple form fields. Obviously your iteration would be as many as number of rows, so you can change that part of the code. But try this:
<?php
if (isset($_POST["SaveComments"]) && isset($_POST["SaveEachComment"]))
{
while(list($key, $val) = each($_POST["SaveEachComment"]))
{
if($val == 'commentbox')
{
echo $_POST['rowcomment'][$key] . "<br />\n";
// do the update here. $val contains the ID
}
}
}
?>
<form id="form1" name="form1" method="post" action="test.php">
<?php for ($i=0; $i<11; $i++) { ?>
<input type="checkbox" <?php echo 'name="SaveEachComment['.$i.']" ';?> value="commentbox" id="commentbox" />
<input type="text" name="rowcomment[<? echo $i?>]" size="55" value="<?php echo $comment;?>" />
<br />
<?php } ?>
<input type="submit" name="SaveComments" value="submit" />
</form>

Can't access array via $_POST

I have the following html code:
<form method="post" action="arrayplay.php">
<input type="checkbox" value="1" name="todelete[]"/>
<input type="checkbox" value="2" name="todelete[]"/>
<input type="checkbox" value="3" name="todelete[]"/>
<input type="checkbox" value="4" name="todelete[]"/>
<input type="submit" value="delete" name="delete"/>
</form>
And the following PHP script:
//arrayplay.php
foreach ($_POST['todelete'] as $id)
{
echo $id . "<br/>";
}
?>
It is supposed to echo out each element value but instead I get an error. I am getting really frustrated. If I use:
<form method="post" action="arrayplay.php">
<?php
$dbc= //connection
$query = "SELECT * FROM email_list";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
echo '<input type="checkbox" value="' . $row['id'] . '" name="todelete[]" />';
echo $row['first_name'];
echo ' ' . $row['last_name'];
echo ' ' . $row['email'];
echo '<br />';
}
mysqli_close($dbc);
?>
<input type="submit" name="submit" value="Remove" />
</form>
It works perfectly fine! Why? The first (hard coded html) holds the exact same value as the one that retrieves them from the database. I am having a real hard time understanding retrieving values from an array with $_POST. Why does name=foo[] create an array? Is it an associative or numeric array? I'm sorry for all of the questions, I'm just really ready to pull my hair out.
if you just named the input foo it would only get one value. because square brackets are commonly used for arrays, foo[] is how in the html form, you indicate an array. of course on the PHP side you just call it foo as you are aware from your working example.
I've tested this and it should work:
<?php
if ($_POST['delete']) {
foreach ($_POST['todelete'] as $id) {
echo $id.' selected<br />';
}
}
?>
<form method="post" action="arrayplay.php">
<input type="checkbox" value="1" name="todelete[]"/>
<input type="checkbox" value="2" name="todelete[]"/>
<input type="checkbox" value="3" name="todelete[]"/>
<input type="checkbox" value="4" name="todelete[]"/>
<input type="submit" value="delete" name="delete"/>
</form>
If you're still having troubles, you can try:
<?php
if ($_POST['delete']) {
for ($i = 0; $i < 4; $i++) {
if (isset($_POST['todelete'][$i])) {
echo $_POST['todelete'][$i].' selected<br />';
}
}
}
?>

Update mysql with $_POST data from while loop

Update mysql with $_POST data from while loop
I'm trying to get this round my head, but i am failing quite hard :[
I have 3 rows in a database which i am echoing out in a while() loop.
A user can change search_terms and then save the fields in mysql, however i don't quite know how to do this, as there are 3 rows, so i can't just do;
<?php
if($_POST['update']) {
mysql_query("....");
}
?>
Here is my code;
<?php
$box_query = mysql_query("SELECT * FROM `ta_boxs`");
while($box = mysql_fetch_array($box_query)) {
echo '<div class="box_content">';
echo '<div class="box">'."\n";
echo '<span class="box_top"></span>';
echo '<div class="box_header"><input type="text" id="title" name="title" class="title-input" value="'.$box['title'].'" /></div>';
echo '<span class="sept"></span>';
echo '<div class="admin-back">';
echo '<form id="form-'.$box['id'].'" name="form-'.$box['id'].'" method="post" action="">';
echo '<p class="sub"><span>Includes:</span> Search for these terms in Twitter Feeds.</p>';
echo '<p class="sub-small">Please enter one word per field or click "add word".</p>';
echo '<p><input type="text" id="search_term_1" name="search_term_1" value="'.$box['search_term_1'].'" class="term-input" />';
echo '<p><input type="text" id="search_term_2" name="search_term_2" value="'.$box['search_term_2'].'" class="term-input" />';
echo '<p><input type="text" id="search_term_3" name="search_term_3" value="'.$box['search_term_3'].'" class="term-input" />';
echo '<span class="hr"></span>';
echo '<p class="sub"><span>Excludes:</span> Ignore these terms in Twitter Feeds.</p>';
echo '<p class="sub-small">Please enter one word per field or click "add word".</p>';
echo '<p><input type="text" id="search_term_1" name="search_term_1" value="'.$box['exc_search_term_1'].'" class="term-input" />';
echo '<p><input type="text" id="search_term_2" name="search_term_2" value="'.$box['exc_search_term_2'].'" class="term-input" />';
echo '<p><input type="text" id="search_term_3" name="search_term_3" value="'.$box['exc_search_term_3'].'" class="term-input" />';
echo '<input type="hidden" id="update" name="update" value="yes" />'
echo '<p><input type="submit" id="update_'.$box['id'].'" name="update_'.$box['id'].'" value="Update" /></p>';
echo '</form>';
echo '</div>';
echo '</div>'."\n";
echo '<span class="box_bottom"></span>';
echo '</div>';
}
?>
There could be 1 output, or 100, but i need a way to save them all, onsubmit. Any ideas?
Since you're outputting each box in a different <form> you'll only every get one back.
If you change:
<input type="hidden" id="update" name="update" value="yes" />
to
<input type="hidden" id="update" name="update" value="' . $box['id'] . '" />
Then you'll be able to look which one was posted back.
I don't think your approach will work because you are generating multiple forms, so PHP will only get the one form that is submitted, and you won't be able to save all the changes on your page.
You might want to consider using one form and naming your inputs like an array (see http://php.net/manual/en/faq.html.php#faq.html.arrays) .
e.g. (simplified)
<form method="post">
<?php while($box = mysql_fetch_array($box_query)): ?>
<!-- div box thing -->
<input name="box[<?php echo $box['id'];?>][search_term_1]" value="<?php echo $box['search_term_1']; ?>">
<input name="box[<?php echo $box['id'];?>][search_term_2]" value="<?php echo $box['search_term_2']; ?>">
<input name="box[<?php echo $box['id'];?>][search_term_3]" value="<?php echo $box['search_term_3']; ?>">
<input name="box[<?php echo $box['id'];?>][exc_search_term_1]" value="<?php echo $box['exc_search_term_1']; ?>">
<input name="box[<?php echo $box['id'];?>][exc_search_term_2]" value="<?php echo $box['exc_search_term_2']; ?>">
<input name="box[<?php echo $box['id'];?>][exc_search_term_3]" value="<?php echo $box['exc_search_term_3']; ?>">
<!-- end div box thing -->
<?php endwhile; ?>
</form>
If you print_r($_POST) after submitting that form you should see that it will be fairly easy to loop over/process.
make one form ,
and in this form set all fields,
one button to submit ,
give to the input elements unique id to every row like you do to the form with the box id

Categories