Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a simple HTML form like this:
<form action="index.php" method="post">
<textarea id="question" name="question"></textarea>
<input type="submit"/>
</form>
And the procedure that I'd like it to be is something like described here:
Type something in the text area and click submit, result displayed:
[... the only text area got blank and be ready for new input ...]
Question 1: Something typed firstly
Type some other thing in the above text area and submit, result displayed:
[... the only text area got blank and be ready for new input ...]
Question 1: Something typed firstly
Question 2: Something typed secondly
And so on...
[... the only text area got blank and be ready for new input ...]
Question 1: Something typed firstly
Question 2: Something typed secondly
...
Question n: Something typed at the n time
Does anyone have an idea or can give me a hint how to do this using only HTML and PHP?
Thank you very much!
You can use hidden inputs if you keep echoing out the id values and the just submitted value. (Also, note how I added a name to the submit)
<form action="index.php" method="post">
<?php
if(isset ($_POST['submit']) {
$oldAnswers = array ();
if(isset($_POST['oldAnswers']) && is_array ( $_POST['oldAnswers'])) {
$oldAnswers = $_POST ['oldAnswers'];
}
if (isset ($_POST ['question']))
$oldAnswers[] = $_POST ['question'];
for($i = 0, $j = 1; $i < count (oldAnswers); $i++, $j++) {
$answer = $oldAnswers [$i];
// display your "previously written" message
echo 'Question ' . $j . ': ' . $answer . "<br>\n";
// echo out hidden inputs
echo '<input name="oldAnswers[]" type="hidden" value="' . $answer . '">';
}
}
?>
<textarea id="question" name="question">< /textarea>
<input name="submit" type="submit">
</form>
See how oldAnswers has [] after it in the name? That'll tell php that it's an array and make it easy to deal with.
If you don't want to put the values in a database you could use a session
session_start();
at the very top of your page and
<?php
if( $_SESSION['counter'] > 0 ) $_SESSION['texts'] = $_SESSION['texts'] . "<br />Question " . $_SESSION['counter'] . ": Something " . $_POST['question'];
$_SESSION['counter']++;
?>
<?php echo $_SESSION['texts']; // put this in a div where you want to see them ?>
This will only clear when the browser is shut.
This is a very crude outline but you could look at tutorials on sessions and how to use them.
You would also need a counter at the bottom of your script to add in the number.
$_SESSION['counter']++;
Using hidden inputs to replace sessions without array or for loop.
<?php
$counter = $counter + (int) $_POST['counter']; // (int) helps sanitise this by forcing type change to integer - any text would be converted to 0
//echo $counter; // for trackng
$texts = $_POST['texts']; // MUST be sanitized and escaped for mysqli
if($counter > 0) $texts = $texts . "<br />Question " . $counter . ": Something " . $_POST['question'];
$counter++;
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<textarea id="question" name="question"></textarea>
<input type="hidden" name="texts" id="texts" value="<?php echo $texts;?>" />
<input type="hidden" name="counter" id="counter" value="<?php echo $counter; ?>" />
<input type="submit"/>
</form>
<?php echo $texts; // put this in a div where you want to see them ?>
Do not use this code without cleaning up the post variables or you will get hacked to bits by hackers. See other posts on preg_replace() and on php.net
Related
I'm looking to implement a very simple quiz using PHP which I'm struggling to find any other examples of to copy. I'm open to various solutions but the requirements are as follows:
Quiz takes place on a single page;
One questions appears at a time, and the user can only see the next question when they correctly answered the current one;
All question types are 'short answer', with users needing to input the correct answer in a text box.
I have been attempting to find a solution using PHP conditional statements (if/else) based on a users answers and my current code looks like this:
<form method="POST" action="">
<label for="question01">1. How many sides does a triangle have?</label>
<input type="text" name="guess01" value="">
<input type="submit">
</form>
<?php
// Process Question 1 Form
$guess01 = $_POST['guess01'];
$guess01 = strtolower($guess01);
$answer01 = "three";
if ($guess01 == $answer01)
{
?>
<p>Correct answer given for question 1!</p>
<form method="POST" action="">
<label for="question02">2. How many sides does a square have?</label>
<input type="text" name="question02" value="" placeholder="Answer here...">
<input type="submit">
</form>
<?php
// Process Question 2 Form
$guess02 = $_POST['guess02'];
$guess02 = strtolower($guess02);
$answer02 = "four";
if ($guess02 == $answer02)
{
?>
<p>Correct answer given for question 2!</p>
<form>
<label for="question02">3. How many sides does a pentagon have?</label>
<input type="text" name="question02" value="" placeholder="Answer here...">
<input type="submit">
</form>
<?php
// Process Question 2 Form
$guess03 = $_POST['guess02'];
$guess03 = strtolower($guess02);
$answer03 = "five";
if ($guess03 == $answer03)
{
?>
<p>Correct answer given for question 3!</p>
<p>Quiz completed!</p>
<?php
}
elseif (empty($guess03))
{
echo "<!-- No Answer Given -->";
}
else
{
echo "<p>Try Again!</p>";
}
?>
<?php
}
elseif (empty($guess02))
{
echo "<!-- No Answer Given -->";
}
else
{
echo "<p>Try Again!</p>";
}
?>
<?php
}
elseif (empty($guess01))
{
echo "<!-- No Answer Given -->";
}
else
{
echo "<p>Try Again!</p>";
}
?>
I'm sure this is very inefficient coding and I'm open to other ways of tackling this. Any help would be very gratefully received. Thank you.
As the form and the validation of your questions are always same only the data changes, you do not need to copy the code. Just put questions and answers in an array and put the number of the current questions in your form.
// Declare all your questions and answers as multi dimensional array
$questionsAndAnwsers = array(array("question" => "1. How many sides does a triangle have?", "answer" => "three"),
array("question" => "2. How many sides does a square have?", "answer" => "four"));
// current question
$currentQuestion = 0;
if(isset($_POST["currentQuestion"])){
$currentQuestion = $_POST["currentQuestion"];
if($_POST["guess"] == $questionsAndAnwsers[$currentQuestion]["answer"]){
// answer was correct, increment your question-counter for the next question
$currentQuestion++;
// print success message
} else {
// question was wrong, counter stays as it is, so same question will be printed
// print failure message
}
}
?>
<form method="POST" action="">
<label for="question"><?php echo ($currentQuestion+1).". ". $questionsAndAnwsers[$currentQuestion]["question"];?></label>
<input type="hidden" name="currentQuestion" value="<?php echo $currentQuestion;?>">
<input type="text" name="guess" value="">
<input type="submit">
</form>
<?php
You have to add a additional if-clause, for the case all questions has been answered.
EDIT:
This is a simple Implementation and it is easy to cheat. As the question number is passed to the browser, the user can alter it (setting it to 9). To close this whole, you have to use session and save the number of the last correct answer in the session on the server.
I am working on a renting website that transfer date from page to another, for example the user enter a date and some information and when he goes to another page he should find the information that he entered in the first page. Everything works fine except that when I add pagination like this: [1] [2] [3] [4] every time I click on a page number in the pagination the POST data will be lost. For example if I clicked number 2 in the pagination I get this message:
Undefined index: date......
I found some solutions which is using get method but I don't know how to use get method in this situation.
What should I change to my code to avoid losing POST data?
here is my full code:
<?php
$date= $_POST['date']; // the post data from previous page
$info= $_POST['info']; // the post data from previous page
?>
<form action="next_page.php" method="post" name="myForm">
<input name="date" type="hidden" value="<?php echo $date; ?>" />
<input name="info" type="hidden" value="<?php echo $info; ?>" />
<?php
include(db.php);
$q="select count(*) \"total\" from users";
$ros1=mysql_query($q,$link);
$row=(mysql_fetch_array($ros1));
$total=$row['total'];
$dis=8;
$total_page=ceil($total/$dis);
$page_cur=(isset($_GET['page']))?$_GET['page']:1;
$k=($page_cur-1)*$dis;
$query="SELECT * FROM cars limit $k,$dis";
$ros=mysql_query($query,$link);
while($row = mysql_fetch_array($ros))
{
echo $row["user_id"];
echo $row["user_name"];
echo $row["user_email"];
}
for($i=1;$i<=$total_page;$i++){
if($page_cur==$i){
echo ' <input type="button" value="'.$i.'"> ';
}
else{
echo ' <input type="button" value="'.$i.'"> ';
}}
?>
<input type="submit" name="userId" value="' .$row['user_id'] . '" />
</form>
You should use GET method instead of POST method.
<?php
$date = $_GET['date']; // the post data from previous page
$info = $_GET['info']; // the post data from previous page
?>
<form action="next_page.php" method="get" name="myForm">
<input name="date" type="hidden" value="<?php echo $date; ?>" />
<input name="info" type="hidden" value="<?php echo $info; ?>" />
<?php
include(db . php);
$q = "select count(*) \"total\" from users";
$ros1 = mysql_query($q, $link);
$row = (mysql_fetch_array($ros1));
$total = $row['total'];
$dis = 8;
$total_page = ceil($total / $dis);
$page_cur = (isset($_GET['page'])) ? $_GET['page'] : 1;
$k = ($page_cur - 1) * $dis;
$query = "SELECT * FROM cars limit $k,$dis";
$ros = mysql_query($query, $link);
while ($row = mysql_fetch_array($ros)) {
echo $row["user_id"];
echo $row["user_name"];
echo $row["user_email"];
}
for ($i = 1; $i <= $total_page; $i++) {
if ($page_cur == $i) {
echo ' <input type="button" value="' . $i . '"> ';
} else {
echo ' $i ';
}
}
?>
<input type="submit" name="userId" value="' .$row['user_id'] . '" />
</form>
You can use PHP sessions to store users input on the server:
PHP Sessions
Keep all the data in $_SESSION and read it from there when it's needed in the page.
Update the stored values when the users inputs something new.
You should store this information somewhere between your http-requests. There are some possible solutions for that:
you can store this information in the database
in session (temporarily store, if you don't need this data in your database)
store in every html page as a hidden field
A good way in my opinion is to start the seach with a POST form and if the results exceed a limit then construct pagination links which really are post forms incorporating the search keyword and target page in the form of hidden variables.
Passing the search keyword as a get parameter needs care (url encode) because urls have limits on the characters they allow (ascii letters and digits, and characters such as /, ~, -, _ etc ) for example a user might search for something in japanese or greek or use symbols.
Passing the search keyword as a session variable also needs care. Consider this scenario: a user has opened multiple result pages, but all pages will hereafter have access to the last processed session saved keyword. Also storing the search keyword in a session requires coordination by the developer such as when to destroy the session variable etc.
I'm trying to add multiple values into a database using PHP from an HTML. However, I can't just refer to the name attribute of the HTML form because each field in the form is generated by a PHP script. I've tried Googling around, but since I don't exactly know what I'm looking for, my search has been futile.
Here's the bit of code that I use to generate the HTML form:
<form action="input_points.php" method="post">
<?php
while($row = mysql_fetch_array($result)) {
echo $row['Name'] . ' <input type="text" name="userpoints">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
I don't know what names are currently in the directory so I need this piece of php to determine what names are in the database. Afterwards, I want to have a bunch of boxes for people to input points (hence the form). I'm having trouble figuring out how to link the particular text box with the user.
For example, if I have a text box for Bob, how would I link up the input text field that contains the number of points Bob earns with Bob's entry in the database?
I know you can do this with regular form fields:
$userpoints = $_POST['userpoints'];
UPDATE members SET points = $userpoints where $user = "Bob";
But since I have multiple users, how do I link up the correct database entry with the right user? Also, how would I determine which boxes are empty and which boxes are updated with a value?
If you want to update multiple filed then are using array
Please changes some code
<form action="input_points.php" method="post">
<?php
$userCount=mysql_num_rows($result);
echo '<input type="hidden" name="userCount" value="' .$userCount. '">';
while($row = mysql_fetch_array($result)) {
echo '<input type="hidden" name="userid[]" value="' .$row['id']. '">'; //Give the uniq id
echo $row['Name'] . ' <input type="text" name="userpoints[]">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
PHP Code -
$userCount = $_POST['userCount'];
for($i=1; $i=$userCount; $i++){
$userpoints = $_POST['userpoints'];
$userid = $_POST['userid'];
//UPDATE members SET points = $userpoints where $user = $userid;
//YOUR CODE HERE
}
The update you're trying to do is not safe unless you treat values to prevent SQL injection... but if you really want it, instead of mysql_fetch_array(), try using mysql_fetch_assoc().
Using mysql_fetch_assoc() you can extract the keys (database field names) with array_keys(). The keys will be your the name property of your form fields and the values of will be the fields' values.
Hope it helps.
You can use an array to store all the data that you need and add a hidden field that contains the missing data:
<form action="input_points.php" method="post">
<?php
for($i=0; $row = mysql_fetch_array($result); $i++ ) {
echo ' <input type="hidden" name="user[0]['name'] value ='". $row['name'] ."'">';
echo $row['Name'] . ' <input type="text" name="user[$i]['points'] ">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
Problem when you hit submit userpoints contain only the last value previous all values are overwritten
solution
name="userpoints"
must be different each time why not you define it in database and then fetch it just like you fetch $row['Name']?
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.
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
How to loop through dynamic form inputs and insert into an array
I have a php script and a form. The php script makes an xml file but what i need is for someone to enter a number and that would set that amount of textboxes that would be for someone to write data for that xml file.
So i need it to write <input type="text" name="a #"> however many times the user enters. Also the name needs to be a number but it counts by one ex:<input type="text" name="1"> <input type="text" name="2">... Thanks
<?php
session_start();
if(isset($_POST['quantity']){
// code here to check isnum and min/max
$count = $_POST['quantity'];
for ($i=1; $i<=$count; $i++){
#$s.= "<input type=text name=".$i."><br>";
}
?>
now just echo out $s in your html
This?
<form method="get" action="">
<div><input type="text" name="num_inputs" value="1" placeholder="Number of inputs"/></div>
</form>
<?php $num_inputs = isset($_GET['num_inputs']) ? $_GET['num_inputs'] : 1; ?>
<form method="post" action="">
<?php for ($i = 0; $i < $num_inputs; $i++) : ?>
<div><input type="text" name="inputs[]"/></div>
<?php endfor ?>
</form>
Edit: yes, an array is much better than input_x. Updated my answer.
I think what you want is an array of form fields.
You want something like this:
<?php
$number_of_textboxes = 5; // you'd get this from a $_GET parameter
echo str_repeat('<input type="text" name="mybox[]" />', $number_of_textboxes);
?>
This will print five text boxes:
<input type="text" name="mybox[]" />
Then, when you reference these boxes' values, you do so like thus:
<?php
foreach ($_POST['mybox'] as $i) {
echo $i;
}
?>
That is, by using "mybox[]" as the name of each input field, you create an array of textboxes, which you can then iterate through.