I am creating a webpage which display a form with 16 questions, each row of input looks like:
<li>*question 1*</li>
<input type="text" name="answer1" style="height: 40px;" size="50" dir="rtl">
<li>*question 2*</li>
<input type="text" name="answer2" style="height: 40px;" size="50" dir="rtl">
and so on - i have 16 (html) lines like that
(by the way, is there a way to prevent this code duplication? this code smells...) and in the end a 'submit' button.
my php script should receive these answers, and put every answer in a variable called "answer(i)" e.g I can write 16 lines of this kind:
if (isset($_POST['submit'])) {
$answer1 = $_POST['answer1'];
$answer2 = $_POST['answer2'];
...ect.
...
}
this (also) feels like a lot of code duplication. is there a way to make it more general and efficient so that if i'm looking to add some new question I won't have to goo through all this again?
I am new to PHP and HTML, and I though of declaring some functions and call them everytime but when I googled keywords like 'html functions' etc. I didn't find and helping info.
edit: The answers labels maybe different than 'answer1, answer2...' and can be a set of different words ('age', 'gender'...)
For the HTML use something like this:
$questions = array(
'question1',
'question2',
//...
);
foreach($question as $id => $qText){
?>
<li>
<?php echo $qText ?>
<input type="text" name="answers[]" style="height: 40px;" size="50" dir="rtl">
</li>
<?php
}
On PHP side you would have your answers in $_POST['answers'], it would be an array. And believe me, if you want to put this values from array into separate variables, it is a red flag: something wrong with your code. You do not want to have a set of answers as independent variables.
You could run a loop to go through the POST array and extract the information into another array.
foreach ($_POST as $k => $v) {
$$k = $v;
}
That will put all of the $_POST data into PHP variables named the same as the form fields generating them (beware you will also get a $submit as well from the button triggering the form).
Is this what you are looking for?
foreach (range(0,16) as $i)
{
${'answer'.$i} = $_POST['answer'.$i];
}
or use extract(), If you apply on your $_POST, keys in your $_POST variable gets assigned as variable.
Here is official documentation.
Related
I'm really new new to php. I consider myself alright at Java, but wanted to get more into web stuff. I like HTML and CSS well enough, but I'm having a lot of trouble with php.
I'm writing a really basic php code. I want it to get info from a user (via form) and add it to an array in php (POST). I then would like to store the array as a session variable and write a for loop that prints out each index in an HTML list.
ISSUES:
1. I don't have a good handle on SESSION, so not sure how to store the array as a session variable.
2. I'm not sure how to reference a specific index of an array in php. I've sorta done it in a java way here, but that needs to change.
--CODE--
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
<?php
$stack = array("");
array_push($stack, $_POST[name]);
for(i < $stack.length){
print_r($stack[i]);
}
?>
To access session variables is easy:
First, you need to call the method session_start() (Make sure, you call it, before sending any HTTP header).
After calling the session_start() method, you will have access to the $_SESSION associative array. You will be able to append anything to this array.
The syntax of the for loop in PHP is as follows:
foreach (array_expression as $value)
statement
or
foreach (array_expression as $key => $value)
statement
I hope that it helps.
First let's see the lines of code in PHP you have written:
I.
$stack = array("");
This creates an array called $stack with a single element of "". $stack[0] will have the value of "". You can name the elements of an associated array, like this:
$stack = array("name" => "value");
In this case $stack["name"] will be "value".
II.
array_push($stack, $_POST[name]);
This is incorrect, since name is not a variable, nor a string. You probably meant:
array_push($stack, $_POST["name"]);
this would have written $_POST["name"] at the end of your array having "", so $stack[1] would have been whatever the value of $_POST["name"]; was.
III.
for(i < $stack.length){
This is incorrect syntax. You have meant
for($i = 0; $i < count($stack); $i++){
Note how $ is put in front of all variables and how similar this for cycle is to a Java for.
IV.
print_r($stack[i]);
Incorrect, you need the the cash ($), otherwise your variables will not cooperate.
print_r($stack[$i]);
You, however, do not check whether this is a POST request or a GET. When the user loads the page, it will be a GET request and when he submits the form, it will be a POST request. The first (GET) request will not have $_POST members ($_POST will be empty), as the form was not submitted yet. And if you check whether it is a POST request, you need to check whether "name" is present in $_POST:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') { //it is a post
if (isset($_POST["name"])) { //name is found inside $_POST
echo "Name is " . $_POST["name"];
}
}
?>
Question1:
$_SESSION is an array, like $stack. You can do something like this:
$_SESSION["name"] = $_POST["name"];
This will create a new element of $_SESSION with the index of "name", however, before such an assignment, you need to make sure the session was started.
Question2:
You reference it by the name of the index, just like in Java, however, in PHP you can have textual indexes as well if you want, while in Java you can only use integers.
Just to quickly update the code you have, to make it somewhat workable:
Html code
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
Php code
<?php
$stack = array("");
if(isset($_POST['name'])){
array_push($stack, $_POST['name']);
for($i=0; $i < count($stack); $i++){
echo($stack[$i]);
}
}
?>
Assuming this is all in welcome.php.
So I'm kind of new to PHP, otherwise I wouldn't be here I guess.
Anyway, I've been trying to practice, and I'm currently building a Shoutbox.
However, I can't seem to save anything other than the previous shout. They seem to keep replacing each other at the first entry of the array. I tried everything I could think of, and it might be something I did with the HTML form name, but I'm clueless.
So, here goes, I hope someone has a lightbulb moment when looking at it.
This is the PHP:
session_start();
$_SESSION['shout'] = array();
array_push($_SESSION['shout'], $_POST['shout'][0]);
$arrayPlace = count($_SESSION['shout']);
foreach($_SESSION['shout'] as $key => $value)
{
$arrayPlace+=1;
echo $arrayPlace;
}
?>
And the HTML:
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<h2>Shoutbox Kevin</h2>
<label for="text">Vul hier uw Shout! in:</label></br>
<input type="text" name="shout[]"/></br>
<input type="submit" value="Verzenden" />
</form>
The problem is: every time you post a shout, you re-initialize the shout-array:
$_SESSION['shout'] = array();
You shoud do that only once (if it doesn't exists):
if (!isset($_SESSION['shout'])) {
$_SESSION['shout'] = array();
}
BTW: You can leave both the [0] in $_POST['shout'][0] and the [] in name="shout[]" away if you let users only shout one message at a time.
I'm using a function that returns a Fetched Array from a Database ( PDO::fetch(PDO::FETCH_ASSOC) ).
this function returns A LOT OF COLUMNS and when I am editing all those columns in a Form, obviously I need the fields to be populate with the current data.
Code (modified for the question):
//returns something like $owner["name"], $owner["lastname"],
//$owner["phone1"] ... and 53 fields more.
$owner = controllerGetOnwer($ownerID);
//So I used a foreach to create VARIABLE VARIABLES
foreach($owner as $key=>$value) {
${$key} = $value; //you get something like $name = <what is in that column>
}
I am gonna use this form in a lot of pages, not only for owners, but also for customers, administrators, and so on... That's why I decided to put the form in a function inside a static class I already used to 'render' all the HTML I will use a lot of times (such as Headers, logos, menus, etc)
//This is inside the HTMLRenderClass
renderTheEditForm() {
?>
<form>
Name: *<br/>
<input type="text" name="personalname" value="<?php if(isset($name)) echo $name; ?>"/><br/><br/>
Last Name: *<br/>
<input type="text" name="personallastname" value="<?php if(isset($lastname)) echo $lastname; ?>"/><br/><br/>
Phone Number 1:<br/>
<input type="text" name="personalphone1" value="<?php if(isset($phone1)) echo $phone1; ?>"/><br/><br/>
<!-- AND 53 FIELDS MORE -->
</form>
<?PHP
}
All the variables that you see inside the VALUE attribute are the same as the ones that are being created dinamically in the FOREACH. When I paste the form HTML code below the Foreach, I can see the data being loaded, but when I use the Function from the HTMLRenderClass I get nothing... I haven't been able to find the reason.
I hope I explained well, thanks beforehand!
It appears that you need to define your variables inside the function or pass them into the function.
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);
}
}
How would I go about parsing incoming form data where the name changes based on section of site like:
<input type="radio" name="Motorola section" value="Ask a question">
where 'Motorola section may be that, or Verizon section, or Blackberry section, etc.
I do not have any control over changing the existing forms unfortunately, so must find a way to work with what is there.
Basically, I need to be able to grab both the name="" data as well as its coresponding value="" data to be able to populate the email that gets sent properly.
Well, you don't receive a HTML form, but just field names and values in $_POST. So you have to look what to make out of that.
Get the known and fixed fields from $_POST and unset() those you've got [to simplify]. Then iterate over the rest. If " section" is the only constant, then watch out for that:
foreach ($_POST as $key=>$value) {
if (stristr($key, "section")) {
$section = $value;
$section_name = $key;
}
}
If there are multiple sections (you didn't say), then build an section=>value array instead.
<form action="formpage.php" method="post">
<input type="radio" name="Motorola_section" value="Ask a question">
</form>
$motorola = $_POST['Motorola_section'];
if ($motorola =='Ask a question')
{
form submit code if motorola is selected
}
Well, first off, you shouldn't have spaces in the name field (even though it should work with them).
Assuming it's a form, you can get the value through the $_POST (for the POST method) and $_GET (for the GET method) variables.
<?php
if ( isset( $_POST['Motorola section'] ) ) // checks if it's set
{
$motoSec = $_POST['Motorola section']; // grab the variable
echo $motoSec; // display it
}
?>
You can also check the variables using print_r( $_GET ) or print_r( $_POST ).