This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
So, I have a problem with getting data from forms and using it in my codes.
this is choose options page:
<form action="options.php" method="post">
<label>Select number of options:</label>
<select name="options">
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br><br>
<input type="submit" name="next" value="Next"><br><br>
</form>
and this is options.php page
<?php
// put your code here
$options = $_POST['options'];
if (isset($_POST['submit'])) {
echo $options;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
Fill in the following fields:<br><br>
<?php
//loop to prompt the user to enter options' details
for ($i = 1; $i <= $options; $i++) {
$optionName = "option$i";
?>
<?php echo 'Option ' . $i; ?><input type="text" name="<?php echo $optionName; ?>"/><br><br>
<?php
}
?>
<input type="submit" name="submit" value="Next"/>
</form>
Somehow I can't get it working. It keeps giving me an error which is "undefined index". I tried to fix it with isset(). I keep doing something wrong here but I don't know what is it. Will someone please help me or suggest some solutions and ways to get it working. I am new at this and started learning last week.
Put these at the beginning of your code to see what's actually posted (it will also show the get values). These format the Get and Post values nicely. I use them all the time. Once you see what's actually posted you'll be able to see what isn't what you're expecting.
echo("<br><br>Get contents:"); echo("<pre>" . print_r($_GET, 1) . "</pre>");
echo("<br>Post contents:"); echo("<pre>" . print_r($_POST, 1) . "</pre>");
exit;
Your $options = $_POST['options']; should be $options = (isset($_POST['options']) ? $_POST['options'] : "");
You have
<input type="submit" name="next" value="Next"><br><br>
Later you check
if (isset($_POST['submit'])) {
The name you give the input, is the key you want to use when looking up the value.
if (isset($_POST['next'])) {
To start you $_POST['submit'] will never be set because there's nothing posting to that field.
If you want to debug this, let's start by getting the output of EVERYTHING posted. We can do that by doing a print_r($_POST); like the following.
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>'
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
Fill in the following fields:<br><br>
<?php
//loop to prompt the user to enter options' details
for ($i = 1; $i <= $options; $i++) {
$optionName = "option$i";
?>
<?php echo 'Option ' . $i; ?><input type="text" name="<?php echo $optionName; ?>"/><br><br>
<?php
}
?>
<input type="submit" name="submit" value="Next"/>
</form>
Then you can see what POST fields are available to you easily and continue coding your project from there.
Related
I have a select list, but on page reload , the data in the list is not saved of corse.
I have fixed this with TextBoxes and Radio buttons by reading the variables from $_GET.
Here is an example of the form I have now:
<form action="" id="exampleForm" method="get">
<input type="checkbox" name="exampleCheckbox" <?php if (isset($_GET['exampleCheckboxStatus'])) {echo "checked";} ?>>Check this
</br>
<select name="exampleList" multiple>
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
</select>
<input type="submit" value="Submit" id="submitButton"> </form>
I would like to keep the values of the 'exampleList' once submitted
(I stay on the same page)
I have seen posts on here that almost look like what I ask, but most of them want to use javascript. Is there an solution for my problem, wich look similiar to what I already have right now? I would like to fix this with php because I dont think I have enough knowledge of Javascript (yet)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var opts = localStorage.getItem('opts'); // get selected items from localStorage key
opts = opts.split(','); // split result from localstorage to array
$('#exampleList').val(opts); // select options with array
});
</script>
<html>
<body>
<select id="exampleList" multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
</body>
</html>
When you POST the form you only need to write the selected option values, comma separated, to the localstorage.
I finally found a solution:
The only flaw is the order of the :)
But since I use a plugin for displaying it does not matter much.
The fix:
I created 2 Array lists
list1 with everying in it
list2 with all selected values
Then I subtract list2 from list1 and dont have duplicates
So I can print both in different print methods.
<?php error_reporting(E_WARNING);
$fruitArray = array("Apple", "Banana", "Cherry", "Durian", "Eggfruit", "Fig", "Grapefruit");
$selectedFruitArray = $_GET['exampleList'];
$fruitArray = array_diff($fruitArray, $selectedFruitArray);
?>
<form action="" method="get">
<select name="exampleList[]" multiple>
<?php
foreach($fruitArray as $value) {
echo "<option value='$value'>$value</option>";
}
foreach($selectedFruitArray as $value) {
echo "<option value='$value' selected>$value</option>";
}
?>
</select>
<input type="submit">
</form>
Use FormRepo, a plugin specially made for retaining form data
on page refreshes.
Its usage is also simple:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="FormRepo.js"></script>
<script>
var $form = $('#input')
, $output = $('#output')
, repo = new FormRepo('restclient')
;
// get the last submitted values back
repo.restore($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
$form.submit(function (e) {
// preserve the last submitted values
repo.preserve($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
});
console.log( repo.all() );
</script>
You can do it by using session. This is the way using it you can store last selected value in session. Session value will not be destroyed even if you reload paga.
For e.g.,
<?php
session_start(); // Other Code
<div>
<p>Subtitle needs to be
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] != "LIKE") echo "checked"; ?> value="LIKE">contain
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] == "=") echo "checked"; ?> value="=">be equal to
</p>
<input type="search" name="subTitleSearchBox" placeholder="filter for subtitle" class="chosenStyle" value="<?php echo $_GET['subTitleSearchBox'];?>">
</div> //Other Code
?>
PHP Code for set value in session after submit :
<?php
session_start(); //Not required if your form action is on same page, else required //Rest code
$_SESSION['subTitleRadio'] = $_GET['subTitleRadio'] // OR $_POST['subTitleRadio']; // Rest code
?>
Same code works for me.
first of all at value parameters to the options, then you can check if exampleList has the right value and use that. for example:
<option value="apple" <?php if (isset($_GET['exampleList']) && $_GET['exampleList'] == "apple") echo "selected=\"selected\""; ?>>Apple</option>
Well, you could try something along these lines. It's a bit lengthy, you could shorten it up quite a bit. By showing it this way, I hope it's simpler to understand.
<form action="" id="exampleForm" method="get">
<?php
if (isset($_GET['exampleCheckboxStatus'])) {
echo '<input type="checkbox" name="exampleCheckbox" checked> Check this';
} else {
echo '<input type="checkbox" name="exampleCheckbox"> Check this';
?>
<br />
<select name="exampleList[]" multiple>
<?php
if( in_array('apple', $_GET['exampleList']) ) {
echo '<option value="apple" selected>Apple</option>';
} else {
echo '<option value="apple">Apple</option>';
}
if( in_array('banana', $_GET['exampleList']) ) {
echo '<option value="banana" selected>Banana</option>';
} else {
echo '<option value="banana">Banana</option>';
}
if( in_array('cherry', $_GET['exampleList']) ) {
echo '<option value="cherry" selected>Cherry</option>';
} else {
echo '<option value="cherry">Cherry</option>';
}
?>
</select>
<input type="submit" value="Submit" id="submitButton">
</form>
Note that I added [] to the select's name and corrected the br tag.
Adding [] will change the type from "string" (text) to an array (several texts). Then we can check what texts are included.
Try it for yourself, play around with the code a bit.
I have an an html form with only <select> element. Below the form I have a text box, I want to update the value of the text box based on the option selected in the form.
I am not sure if this is possible in PHP, I know I can do it with Javascript/Jquery, but I am working on a school project and its a PHP project. My teacher has done it but Im not sure if he used PHP.
Here is my code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books">
<?php
$books = simplexml_load_file("books.xml");
foreach($books->book as $book){
$code = $book->code;
$title = $book->title;
echo "<option value='$code'>$code: $title</option>";
}
?>
</select>
</form>
<?php
$choice = $_POST['books'];
echo "<input type='text' value='$choice'>";
?>
When the page first loads I want the value from the selected option to be in the text box. I am not sure how I could go about doing this in PHP. Help would be appreciated.
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books" onchange="javascript:document.form.submit();">
<?php
$books = simplexml_load_file("books.xml");
foreach($books->book as $book){
$code = $book->code;
$title = $book->title;
echo "<option value='$code'>$code: $title</option>";
}
?>
</select>
</form>
<?php
$choice = isset($_POST['books'])?$_POST['books']:'';
echo "<input type='text' value='$choice'>";
?>
Edit, as a pure PHP solution with a submit button, which will load data on initial page load then load data with the submit button as per selection.
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books">
<?php
$books = simplexml_load_file("books.xml");
foreach($books->book as $book){
$code = $book->code;
$title = $book->title;
echo "<option value='$code'>$code: $title</option>";
}
?>
</select>
<input type="submit" value="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$choice = isset($_POST['books']) ? $_POST['books'] : $books->book[0]->code;
echo "<input type='text' value='$choice'>";
}
else{
$choice = isset($_POST['books']) ? $_POST['books'] : $books->book[0]->code;
echo "<input type='text' value='$choice'>";
}
?>
Original answer with onchange
The following would work, using Javascript and getElementById which would echo the selection in a text box using an onchange function.
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books" onchange="update_textbox()" id="id_books">
<?php
$books = simplexml_load_file("books.xml");
foreach($books->book as $book){
$code = $book->code;
$title = $book->title;
echo "<option value='$code'>$code: $title</option>";
}
?>
</select>
</form>
<?php
$choice = isset($_POST['books']) ? $_POST['books'] : '';
echo "<input type='text' value='$choice' id='showit'>";
?>
<script>
function update_textbox(){
var selectbox = document.getElementById('id_books');
var id_books = selectbox[selectbox.selectedIndex].text;
document.getElementById('showit').value=id_books ;
}
</script>
To load data into the text box at initial page load, use:
Replace:
$choice = isset($_POST['books']) ? $_POST['books'] : '';
with:
$choice = isset($_POST['books']) ? $_POST['books'] : $books->book[0]->code;
When you first load the page, there are no POST data, so you could set $choice to the first book in list:
$choice = isset($_POST['books']) ? $_POST['books'] : $books->book[0]->code;
But you have to udnerstand the difference between PHP and JavaScript in here.
PHP can only change the value, when there is a request on the server as it is a server-side language. If you wish to update the value instantly, without submiting the form, you need to use JavaScript.
if it must be purely PHP, then put a submit button on your form for when a selection is made. This will set the value you are looking for. Others have provided samples on how to do this form submission automatically with javascript, but the end result is the same.
You can do it with PHP, it looks as though you're just missing the submit button to actually post the selection.
To submit the form without a submit button, you need to use javascript, eg.
<select onchange="this.form.submit()">....</select>
Below is a simple example (static options rather than xml) that also sets the selected option in the select (IMO this is a more practical use than printing it in the text input)
<?php
$val = isset($_REQUEST['books']) ? $_REQUEST['books'] : null;
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books" onchange="this.form.submit()">
<option value=>Choose a book</option>
<option<?php if($val && $val === 'opt 1'){ print ' selected';}?>>opt 1</option>
<option<?php if($val && $val === 'opt 2'){ print ' selected';}?>>opt 2</option>
</select>
<noscript><button type="submit">Submit</button></noscript>
</form>
<?php if($val){ ?>
<input type="text" value="<?php echo $_REQUEST['books']; ?>">
<?php } ?>
This is probably ok just for a school exercise, but in the real world you would probably want to sanitize any user input ($_REQUEST['book'] / $_POST['book']) and use a better templating engine than vanilla PHP (I like Twig) to help separate presentation from functional logic.
I have inside loop some fields for send inside form with other fields :
<?php
for($f=1;$f<=3;$f++)
{
?>
<input type="text" name="friend['email_<?php echo $f;?>']" value="<?php echo $_POST['friend']['email_'.$f.''];?>">
<?php
}
?>
When i send from form i need get the value of each field if no empty , i think the problem it´s in no recover the value send from the form , i don´t know if i writte right
Ony it´s that problem , thank´s , the best regards
I think the problem here is that you have single quotes around email_<?php echo $f; ?> - in POST data, these are not needed. So, you would have:
<form action="myPage.php" method="POST">
<?php for ($f=1;$f<=3;$f++) { ?>
<input type="text" name="friend[email_<?php echo $f; ?>]" value="<?php echo ... ?>">
<?php } ?>
<input type="submit">
</form>
PHP will parse POST data into associative arrays, so you will get back a 'friend' object in $_POST. You can access this like so:
<?php
$friends = isset($_POST['friend']) ? $_POST['friend'] : array();
print_r($friends);
?>
I'm not sure if i'm getting it right. You must send your form data in order to manipulate it. For example if you want to print all the form data:
Client Side:
<form action="boo.php" method="POST">
<input type="text" name="name">
<input type="text" name="age">
<input type="submit">
</form>
Server Side:
<?php
$name = "";
$age = "";
if( isset($_POST['name']) && isset($_POST['age']) )
{
$name = htmlspecialchars($_POST['name']);
$age = htmlspecialchars($_POST['age']);
}
echo 'Your name is ' . $name . ' and your age is ' . $age;
?>
If you are trying to retain the values even after invalid input you can just echo the input in value attribute of the input field.
here is my code:
<?php
ob_start();
session_start();
require 'connection.php';
require 'core.inc.php';
?>
<?php
$take_thread_pid_query = #mysql_query(" select pid from threads ");
$row_take_thread_pid = mysql_fetch_array($take_thread_pid_query);
$pid = $row_take_thread_pid['pid'];
while($row_take_thread_pid = #mysql_fetch_array($take_thread_pid_query))
{
?>
<form action="kill_threads.php" method="POST" >
<label> <?php echo "<br/><br/>thread".$row_take_thread_pid['pid']; ?><input type="submit" value = " <?php echo $row_take_thread_pid['pid'];?> " name = " <?php echo
$row_take_thread_pid['pid']; ?> " /> </label>
<?php }?>
</form>
<?php
$t = "4756";//[4756 is on of the pids in my thread table].this is for testing but doesnt works,it cant find any button with this name.
if ( isset($_POST[$t] ) ) echo "im a killed thread..";
?>
The big problem is that im trying to give different names to each button i create,but it seems this is not working because when im trying to see if a button isset['???']
What i have to do...?
For example
thread 1 [button 1]
thread 2 [button 2]
thread 3 [button 3 ]
So if now i click button 1 i want thread1 row deleted from database.
phpmyadmin works like this.
Im so complicated..please help,thanks in advance.
Your code is:
value = " <?php echo $row_take_thread_pid['pid'];?> "
name = " <?php echo $row_take_thread_pid['pid']; ?> "
You are placing spaces before and after the php text so you either have to remove the spaces or code for them
I would suggest you to use another hidden input element within the form instead of doing it with submit form, in this way you can kill all the threads with one if block by passing thread id to it.
while($row_take_thread_pid = #mysql_fetch_array($take_thread_pid_query))
{
?>
<form action="kill_threads.php" method="POST" >
<label> <?php echo "<br/><br/>thread".$row_take_thread_pid['pid']; ?>
<input type="hidden" name="pid" value="<?php echo $row_take_thread_pid['pid'];?>" />
<input type="submit" value = "Delete" name = "delete_thread" /> </label> <?php }?>
</form>
<?php
$t = "4756";//[4756 is on of the pids in my thread table].this is for testing but doesnt works,it cant find any button with this name.
if ( isset($_POST[$t] ) ) echo "im a killed thread..";
?>
Another problem you may come across is using multiple forms without name and id. So add a dynamic number in the form tag like like this
<form name="<?php echo $i; ?>" id="<?php echo $i; ?>" action="kill_threads.php" method="POST" >
Here $i is counter variable or you can use $row_take_thread_pid['pid'] for this purpose.
so i have this code fragment here..
if($numTF > 0)
{
echo "TRUE-AND-FALSE QUESTIONS: Enter them below followed by their correct answer.";
echo "<br>";?>
<form method="post" action="" name="quizform">
<?php for ($i=1; $i<=$numTF; $i++)
{
echo "Question"." ".$i;
?>`
<p><textarea name='question<?php echo $i; ?>' rows=3 cols=90></textarea></p>
<input type="radio" name="answer<?php echo $i; ?>" value="True"> True
<input type='radio' name="answer<?php echo $i; ?>" value="False"> False<br><br><br>
<?php
}
}
... i am making a quiz maker in php...
the first thing to do is to set up the desired number of questions, so the value entered will go on the $numTF variable. Depending on the entered value, the textarea part will be printed. and there will be different names for each text area. AND THE CODE ABOVE IS WHERE U PRINT THE FORMS AFTER U ENTER THE DESIRED VALUE.
The next thing is to save that in a database. since the name of each textarea will be based on a variable value($i) that is used in a loop (name="answer") , HOW CAN I USE IT IN $_POST??? Like, would i do it like this?? ($_POST['question']).
HOW CAN I SAVE THESE QUESTIONS IN A DATABASE??
PLEASE HELP ME ....
I WOULD BE SO MUCH MUCH MUCH GRATEFUL FOR A LIL HELP.
<?
var_dump($_POST);
?>
<form method="post">
<?
$numTF=4;
if($numTF > 0)
{
echo "TRUE-AND-FALSE QUESTIONS: Enter them below followed by their correct answer.";
echo "<br>";?>
<form method="post" action="" name="quizform">
<?php for ($i=1; $i<=$numTF; $i++)
{
echo "Question"." ".$i;
?>`
<p><textarea name='question[<?php echo $i; ?>]' rows=3 cols=90></textarea></p>
<input type="radio" name="answer[<?php echo $i; ?>]" value="True"> True
<input type='radio' name="answer[<?php echo $i; ?>]" value="False"> False<br><br><br>
<?php
}
}
?>
<input type="submit" name="submit" value="submit"/>
</form>
Use $_POST['question'][1] // To get first question
Use $_POST['answer'][1] // To get first answer
Use loop to get all question and answers
I agree with Sachin as far as using name='question[]'. To answer question a little more as far as storing it in a database. Personally I would use a JSON array.
$store_answers = json_encode($_POST['answer']);
$store_questions = json_encode($_POST['question']);
Then just store $store_string in a TEXT field in your database. Then when you pull it back out of the database you can simple use:
$answers = json_decode($store_answers);
$questions = json_decode($store_questions);
Then you can loop through using a foreach like so:
foreach($questions as $key=>$question) {
echo "Question $key = {$answers[$key]} <br />";
}
This will display the results for each question.