DEMO.PHP
<form action = "test.php" method="post">
<input type="checkbox" name="vehicle[]" value="'Peter'=>'35'">I have a bike<br>
<input type="checkbox" name="vehicle[]" value="'Ben'=>'37'">I have a car <br>
<input type="submit" value="Submit">
</form>
test.php
<?php
if(isset ($_POST["vehicle"]))
{
$v = $_POST["vehicle"];
foreach($v as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
}
?>
My $x didnt get Peter or Ben?
How can I get the key and value separately?
If you name your fields ending in [], then PHP will construct a regular array from them.
Using => in the value will have no special meaning.
If you want to specify the key names that PHP will parse the form data into, then you do so in the name:
name="vehicle[Peter]" value="35"
Related
i'm doing this exercise to understand te concepts and syntax of php.The error i get is that the array is not being appended by a new entry from a text box, if i hard code the values the program works fine and prints the array values. but as soon as i put the variable it just assign a new value to the [0] index.
here is the code:
<label for="Name">Student Name:
<input type="text" name="StdName" placeholder="Your name">
</label>
<label for="Name">Grade:
<input type="text" name="StdGrade" placeholder="Your Grade">
</label>
<input type="submit" name="submit"value="submit">
</form>
<?php
// Associative array new
$studentName = $_POST['StdName'];
$studentGrade = $_POST['StdGrade'];
$classGrades = Array();
$classGrades['name'][] = $studentName;
$classGrades['grade'][] = $studentGrade;
echo "<br> <br> Your name is: $studentName and your grade is: $studentGrade <br> <br>";
foreach($classGrades as $key=>$value){
echo join($value,' <br>');
}
?>```
Your loop is wrong. You have separate name and grade arrays, so that's what you need to loop over:
foreach ($classGrades['name'] as $index => $name) {
$grade = $classGrades['name'][$index];
echo "$name<br>$grade<br>";
}
But it would be better if you didn't create separate array and kept the name and grade together in a single associative array:
$classGrades[] = ['name' => $studentName, 'grade' => $studentGrade];
Then your loop would look like:
foreach ($classGrades as $grade) {
echo $grade['name'] . "<br>" . $grade['grade'] . "<br>";
}
If you want the variable to persist between form submissions, you need to use a session variable.
Put
<?php
session_start();
at the beginning of the script. Then use $_SESSION['classGrades'] instead of $classGrades, and initialize it like this:
if (!isset($_SESSION['classGrades'])) {
$_SESSION['classGrades'] = array();
}
Basically you need to store your values, in some database.
Here is a simple start using a json file named students.json as database. That file will be created along your php file in the same folder, if not existing.
First you was missing the form elements and the method (by default it uses GET, thus this was not working).
Testing with isset() avoids populating the database with empty values, at page load or refreshs.
This is not very secure as such, you will have to work on that later on. Hint: What if a user insert a quote ' or " in his name?
<form method="post">
<label for="Name">Student Name:
<input type="text" name="StdName" placeholder="Your name">
</label>
<label for="Name">Grade:
<input type="text" name="StdGrade" placeholder="Your Grade">
</label>
<input type="submit" name="submit"value="submit">
</form>
<?php
if (!is_file("students.json")){
file_put_contents("students.json", json_encode([]) );
}
$classGrades = json_decode(file_get_contents("students.json"),true);
if (isset($_POST['StdName']) && isset($_POST['StdGrade'])){
var_dump($classGrades);
$studentName = $_POST['StdName'];
$studentGrade = $_POST['StdGrade'];
$classGrades['name'][] = $studentName;
$classGrades['grade'][] = $studentGrade;
echo "<br> <br> Your name is: $studentName and your grade is: $studentGrade <br> <br>";
file_put_contents("students.json",json_encode($classGrades));
}
echo "<table><tr><th>Name</th><th>Grade</th></tr>";
for ($i = 0;$i < count($classGrades['name']);$i++){
echo "<tr><td>".$classGrades['name'][$i] . "</td><td> " .$classGrades['grade'][$i] . "</td></tr>";
}
echo "</table>";
So I'm doing this website with Joomla and I don't have much experience with Joomla.
I just want to get the values of some checkboxes and print them into a text area.
I have the script already, I just need to implement it.
Here the raw Html code of the checkboxes:
<div class="checkboxShop">
<form action="" method="post">
<input type="checkbox" value="1" id="checkboxShopInput" name="shop" />
<label for="checkboxShopInput"></label>
</form>
</div>
And Here is the raw Html code of the submit button:
<form action="/Flex/index.php/shop" method="post">
<input type="submit" value="Buy">
</form>
All I want is to get all the values of the checkboxes and add them to a textarea in index.php/shop. I wrote this code to get the values but i don't know where to add this:
<?php
if(!empty($_POST['shop'])) {
foreach($_POST['shop'] as $check) {
echo $check; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
echo "<input type='text' name='message' value='" . $check . "'>"
}
}
?>
I've read that i need this but I'm not sure how: <?php include "name_of_script.php";?>
Thanks for the help
I searched and can't find an answer to this and nothing I try works. In this form, for each image (pix) and there the user enters the number of copies to be produced.
I know how to build the array for each individually when the submit button is clicked but I can't get both arrays to relate to each other. I want to produce something like: 01.jpg - 3 copies, 02.jpg - 1 copy etc etc.
How can I achieve this?
Thanks
This is my form:
<form action="self.php" method="post">
<img src="01.jpg" alt="01.jpg">
<input type="checkbox" name="pix[]" value="01.jpg_album">
<input type="text" name="quantity[]">
<img src="02.jpg" alt="02.jpg">
<input type="checkbox" name="pix[]" value="02.jpg_extra">
<input type="text" name="quantity[]">
<img src="03.jpg" alt="03.jpg">
<input type="checkbox" name="pix[]" value="03.jpg_extra">
<input type="text" name="quantity[]">
<input type="submit" name="submit">
</form>
This is how I extract the values returned:
echo implode('<br>', $_POST['pix']);
echo implode('<br>', $_POST['quantity']);
EDITED: FURTHER to my question above and in response to the second code posted by Rajdeep ... I've separated the two processes. The first was to determine whether the client wanted the image for his wedding album, so I did:
$arr = array("01", "02", "03");
echo "<h3>Images required for album: </h3>";
foreach($_POST as $key => $value){
if(in_array($key, $arr)){
$var = $value . ".jpg";
if(isset($_POST[$value]) && !empty($_POST[$value])){
echo $var."<br />";
}//endif
} //endif
}// end foreach
This output was:
03.jpg
04.jpg
23.jpg
etc
Then, I wanted to know if he needed any additional individual prints and this code (sort of) worked for that:
echo "<h3>Extras required: </h3>";
$noextras = false;
foreach($_POST as $key => $value){
if(in_array($key, $arr)){
$var = $value . ".jpg - ";
if(isset($_POST[$value . "_extra"]) && !empty($_POST[$value . "_extra"])){
$sum = $_POST[$value . '_extra'];
if($sum == 1) {
$var .= $sum ." copy <br />";
} else {
$var .= $sum . " copies <br />";
}
echo $var;
} else if(empty($_POST[$value . "_extra"])) { $noextras = true; }
} //endif in_array
}// end foreach
if($noextras) { echo "No extra copies needed.";}
And the output from this was something like
03.jpg - 5 copies
04.jpg - 2 copies
23.jpg - 1 copy
I then discovered a snag. This permitted extra copied to be selected for ONLY for images that were selected for inclusion in the album. I have tried various variations on the code and I am coming up with a blank.
So, I've changed this to a two step process. First page, the person selects the images for the album, which when submitted go to a confirmation page to show what had been selected. Once he clicks the 'confirm' button an email goes to me and him.
Clicking the confirm button also goes to a Thank You page which then refreshes into the second page for ordering individual prints. Here he can select how many copies of a print he needs and this works well with Rajdeep's first 'merged' code BUT it only works for one selection.
I've expanded the selection and this is where I am currently having trouble. He has a choice to decides how many copies he needs of each of the four different sizes available (7x6, 9x5, 10x8, 12x8). I am able to process one size only but am having trouble with expanding it to four inputs.
Any suggestions?
Thanks.
Instead of two different <input> tags with checkbox and text attribute, use only one <input> with number attribute for each image. And make the name attribute as the name of your image, like this:
<form action="self.php" method="post">
<img src="01.jpg" alt="01.jpg" />
<input type="number" name="01" min="0" />
<img src="02.jpg" alt="02.jpg" />
<input type="number" name="02" min="0" />
<img src="03.jpg" alt="03.jpg" />
<input type="number" name="03" min="0" />
<input type="submit" name="submit" value="submit" />
</form>
And this is how you can process the form,
if(isset($_POST['submit'])){
foreach($_POST as $key => $value){
if($key == "submit"){
continue;
}
if(!empty($value)){
$var = $key . ".jpg - " . $value;
if($value == 1){
$var .= " copy";
}else{
$var .= " copies";
}
$var .= "<br />";
echo $var;
}
}
}
A sample output would be like this:
01.jpg - 3 copies
02.jpg - 1 copy
03.jpg - 5 copies
Edited:
Based on your requirement, use <input type="checkbox" name="xx" value="xx" /> for selecting the image(i.e when user wants this image to be included in photo album) and use <input type="number" name="xx_extra" min="1" /> for keeping track of how many extra copies of this image user wants.
So your HTML code should be like this:
<form action="self.php" method="post">
<img src="01.jpg" alt="01.jpg" />
<input type="checkbox" name="01" value="01" />
<input type="number" name="01_extra" min="1" />
<img src="02.jpg" alt="02.jpg" />
<input type="checkbox" name="02" value="02" />
<input type="number" name="02_extra" min="1" />
<img src="03.jpg" alt="03.jpg" />
<input type="checkbox" name="03" value="03" />
<input type="number" name="03_extra" min="1" />
<input type="submit" name="submit" value="submit" />
</form>
And this is how you can process the form,
<?php
if(isset($_POST['submit'])){
$arr = array("01", "02", "03");
foreach($_POST as $key => $value){
if(in_array($key, $arr)){
$var = $value . ".jpg - ";
if(isset($_POST[$value . "_extra"]) && !empty($_POST[$value . "_extra"])){
$sum = $_POST[$value . '_extra'] + 1;
$var .= $sum . " copies <br />";
}else{
$var .= "1 copy <br />";
}
echo $var;
}
}
}
?>
Attempt 1: This shows what I want to achieve. The same array but different key and value pair.When printed, it list out all the keys and values.
<?php
$rental[]=array('day'=>1,'rate'=>10);
$rental[]=array('day'=>2,'rate'=>20);
$rental[]=array('day'=>3,'rate'=>30);
$rental[]=array('day'=>4,'rate'=>40);
print_r($rental);
?>
Attempt 2: Now, I'm using a single form to submit multiple times.I expect the key and values to be stored inside an array each time the form is submitted. But what happens is, the last value pair overwrites the previous one.Therefore only one pair is shown. So far, I can store them with the help of session. But I just wonder if there's a way to achieve it via php array on the same page?
<?php
$rental[]=array('day'=>$_POST['days'],'rate'=>$_POST['rental']);
print_r($rental);
?>
<form action="#" method="post">
Number of Days: <input type="text" name="days" value=""><br/>
Rental rate: <input type="text" name="rental" value=""><br/>
<input type="submit" name="add_rental_rate" value="Add Rental Rate">
</form>
You can use session to achieve what you want, see this code:
<?php
session_start();
if(isset($_POST['days']) && isset($_POST['rental'])){
$_SESSION['info'][] = array($_POST['days'] => $_POST['rental']);
}
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
foreach($_SESSION['info'][$i] as $days => $rental){
echo '<p>' . $days . '<br>';
echo $rental . '</p>';
}
}
}
?>
<form action="#" method="post">
Number of Days: <input type="text" name="days" value=""><br/>
Rental rate: <input type="text" name="rental" value=""><br/>
<input type="submit" name="add_rental_rate" value="Add Rental Rate">
</form>
You should read some docs about session:
http://php.net/manual/en/intro.session.php
Using the following code I am attempting to:
Test to see if one of the dynamically assigned field names has been submitted;
Use the "Actionable Code" to process the submitted information.
My problem lies in I am incapable of retrieving the appropriate dynamic variable name. $this->get_field_name('email_to') will output a name variable such as widget-mywidget[3][email_to]; but to access this value via PHP I need it in the form of $_POST['widget-mywidget'][3]['email_to'].
How can I go about solving this dilemma?
OUTPUTTED HTML:
<form id="widget-mywidget-3-osiris_contact" method="post" action="">
<fieldset>
<input type="text" name="widget-mywidget[3][user_name]">
<input type="text" name="widget-mywidget[3][user_email]">
<textarea name="widget-mywidget[3][user_message]"></textarea>
</fieldset>
<fieldset>
<input type="hidden" name="widget-mywidget[3][email_to]" value="">
<input type="hidden" name="widget-mywidget[3][email_subject]" value="">
<button type="submit" name="widget-mywidget[3][email_send]">Send</button>
</fieldset>
</form>
PROCESSING PHP:
if(in_array($this->get_field_name('email_to'), $_POST)){ // <--- Where I need help.
// Actionable Code
}
This is what $this->get_field_name does:
function get_field_name($field_name) {
return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
}
I suggest that you print_r($_POST) and compare it visually for better debugging...
(Or use a debugger...)
$thing = "widget-mywidget[3][email_to]";
$exp = explode("[", $thing);
$get_it = $_POST['".$exp[0]."[".$exp[1]."[".$exp[2]."'];
Try, if it works.