I have a form that includes the first name and last name of a person. The user can add multiple people using a link, that creates new input fields via JS. Here's an example of a form that includes 2 people:
<form action="" method="post">
<input type="text" class="required" name="people[first][]" />
<input type="text" class="required" name="people[last][]" />
<input type="text" class="required" name="people[first][]" />
<input type="text" class="required" name="people[last][]" />
<input type="submit" name="submit">
</form>
I'm trying to figure out a way to insert this data into the database. I've tried using:
foreach ($_POST['people'] as $person) {
foreach ($person as $value) {
echo $value . '<br/>';
}
}
.. which results in
first name 1
first name 2
last name 1
last name 2
I'm trying to group the results somehow so I can insert a new row for each first name x + last name x combination.
Create the input elements like this:
<input type="text" name="people[0][first]" />
<input type="text" name="people[0][last]" />
<input type="text" name="people[1][first]" />
<input type="text" name="people[1][last]" />
In your PHP:
foreach ($_POST['people'] as $person) {
echo $person['first'].' '.$person['last'].'<br />';
}
$_POST['people']['first'] is an array of first names.
$_POST['people']['last'] is an array of last names.
You can merge them into an array of arrays like this:
$people = $_POST['people'];
$length = count($people['first']);
for($i = 0; $i < $length; $i++)
$temp[] = array('first' => $people['first'][$i], 'last' => $people['last'][$i]);
$people = $temp;
The resulting array in $people will be an array of associative arrays, and might look like:
Array
(
[0] => Array
(
[first] => Jim
[last] => Smith
)
[1] => Array
(
[first] => Jenny
[last] => Johnson
)
)
which is equivalent to the array you would get by modifying your HTML as bsdnoobz has shown you can do as well. Iterating through it would be the same too:
foreach ($people as $person) {
echo $person['first'] . ' ' . $person['last'] . '<br />';
}
Related
i design a form and submit it to PHP to process. i put several "input" in this table of form and need to pass them to an array. the "input is not fixed", may be 10 or 20 or more, it can be added or deleted. my question is: i don't know how to pass this "value" to php variable , which in another Multidimensional Arrays
html:
1 <input type="text" name="description[]" id="1">
2 <input type="text" name="description[]" id="2">
3 <input type="text" name="description[]" id="3">.....
15 <input type="text" name="description[]" id="15">
php:
$detail = array ('aa' => 'non','bb' => array('0' => array('Description'=>$_POST['description'][0],'DD'=>'CN'),'1'=>array('Description'=>$_POST['description'][1],'DD'=>'CN')...
as I understand your question what you need is that to push this to the existing array with already have a value:
<?php
$detail = array('some_existing_value' => 'value1');
for($i = 0; $i < count($description); $i++) {
array_push($detail, $description[$i]);
}
//then you may try if the value already pushed in arrays
var_dump($detail);
?>
This question already has answers here:
Get all variables sent with POST?
(6 answers)
How to grab all variables in a post (PHP)
(5 answers)
How do I get the key values from $_POST?
(6 answers)
Retrieve post array values
(6 answers)
How to get an array of data from $_POST
(3 answers)
Closed 5 years ago.
I have an HTML-form with 3 inputs of type text and one input of type submit, where a name of an animal is to be inserted into each textbox. The data should then be inserted into a PHP-array.
This is my HTML-form:
<form action="Test.php" method="post" name="myForm" id="myForm">
<input type="text" placeholder="Enter animal one..." name="animal1" id="animal1">
<input type="text" placeholder="Enter animal two..." name="animal2" id="animal2">
<input type="text" placeholder="Enter animal three..." name="animal3" id="animal3">
<input type="submit" value="Submit" name="send" id="send">
</form>
And this is my much experimental PHP-code:
<?php
if (isset ($_POST["send"])) {
$farmAnimals = $_POST["animal1"];
$farmAnimals = $_POST["animal2"];
$farmAnimals = $_POST["animal3"];
}
// As a test, I tried to echo the saved data
echo $farmAnimals;
?>
This does not work, as the data doesn't magically turn into an array, unfortunately, which I thought it would.
I have also tried this:
<?php
if (isset ($_POST["send"])) {
$farmAnimals = $_POST["animal1", "animal2", "animal3"];
}
echo $farmAnimals;
?>
This gives me an error message. How can I insert this data into a PHP-array?
First initialize the $farmAnimals as array, then you can push elements
if (isset ($_POST["send"])) {
$farmAnimals = array();
$farmAnimals[] = $_POST["animal1"];
$farmAnimals[] = $_POST["animal2"];
$farmAnimals[] = $_POST["animal3"];
print_r($farmAnimals);
}
Try this:
$string = "";
foreach($_POST as $value){
$string .= $value . ",";
}
Or this:
$string = implode(',', $_POST);
If you change the text field names to animal[] then you have an array of animal names when it is posted
<form action='Test.php' method='post'>
<input type='text' placeholder='Enter animal one...' name='animal[]' />
<input type='text' placeholder='Enter animal two...' name='animal[]' />
<input type='text' placeholder='Enter animal three...' name='animal[]' />
<input type='submit' value='Submit' name='send' id='send'>
</form>
You can then process that array in php easily for whatever end purpose you have - the output of which would be like this:
Array
(
[animal] => Array
(
[0] => giraffe
[1] => elephant
[2] => rhinocerous
)
[send] => Submit
)
To access these animals as an array in their own right you could do:
$animals=array_values( $_POST['animal'] );
Try naming your input fields like this:
<form action="Test.php" method="post" name="myForm" id="myForm">
<input type="text" placeholder="Enter animal one..." name="animal[0]" id="animal1">
<input type="text" placeholder="Enter animal two..." name="animal[1]" id="animal2">
<input type="text" placeholder="Enter animal three..." name="animal[2]" id="animal3">
<input type="submit" value="Submit" name="send" id="send">
</form>
This way you be able to access those values in your PHP code like this:
if(isset($_POST["send"])) {
$farmAnimals = $_POST["animal"];
}
var_dump($farmAnimals);
// Array( [0] => Animal1, [1] => Animal2, [2] => Animal3 )
// Where Animal1,... are the values entered by the user.
// You can access them by $farmAnimals[x] where x is the desired index.
Tip: You can use empty() to check a variable for existance and if it has a "truthy" value (a value which evaluates to true). It will not throw an exception, if the variable is not defined at all. See PHP - empty() for details.
Futher reference about the superglobal $_POST array, showing this "array generating name" approach: https://secure.php.net/manual/en/reserved.variables.post.php#87650
Edit:
I just saw, that you actually overwrite your $farmAnimals variable each time. You should use the array(val1, val2, ...) with an arbitray amount of parameters to generate an numeric array.
If you prefer an associative array do this:
$myArray = array(
key1 => value1,
key2 => value2,
....
);
To append a value on an existing array at the next free index use this syntax:
// This array contains numbers 1 to 3 in fields 0 to 2
$filledArray = array(1,2,3);
$filledArray[] = "next item";
// Now the array looks like this:
// [0 => 1, 1 => 2, 2 => 3, 3 => "next item"]
I have two inputs as follows:
<form method="post" action="#">
<input type="text" name="prod[][prod]"><input type="text" name="prod[][qty]">
<input type="text" name="prod[][prod]"><input type="text" name="prod[][qty]">
/* The second input set was generated dynamically via jQuery. */
</form>
I want to pair each product with its' quantity with multidimensional array with following codes (thanks to #Styphon):
$works = $_POST['prod'];
foreach ($works as $work => $value) {
echo $value['prod'] ." ". $value['qty'] ."<br>";
}
However, the results was weird as follows
aa
11
bb
22
Appreciated if someone can help on this.
You need a multidimensional array. Something like this:
<form>
<input type="text" name="prods[0][prod]">
<input type="text" name="prods[0][qty]">
<input type="text" name="prods[1][prod]">
<input type="text" name="prods[1][qty]">
</form>
Then in PHP you can access the multidimensional array using $_POST['prods'], you can loop through each one using a foreach like this:
foreach ( $_POST['prods'] as $i => $arr )
{
echo "$i is prod {$arr['prod']} and qty {$arr['qty']}<br>";
}
I am learning php and having trouble understanding how to use an associate arrays with user inputs. I will eventually need to sort my array by a key value but for now I just dont know if I am doing it correctly. The examples in the book didn't show how to get a user input and use it in an array just predetermine values. Can someone please help me and tell me if I on the right track. I understand I need to use the $_POST method to get the information for the array but I just cant figure out how to use it. When i upload what i have i keep getting error
<HTML>
<HEAD>
<TITLE>Student Form</TITLE>
</HEAD>
<BODY>
<FORM METHOD="post" ACTION="final_project.php">
<P>Please enter your name: <INPUT TYPE="text" NAME="txtname" SIZE= 10></P>
<P>Please enter your id: <INPUT TYPE="text" NAME="txtid" SIZE= 10></P>
<P>Please enter your address: <INPUT TYPE="text" NAME="txtaddress" SIZE= 10></P>
<P>Please enter your cell phone number: <INPUT TYPE="text" NAME="txtcell" SIZE= 10></P>
<P>Please enter your Major: <INPUT TYPE="text" NAME="txtmajor" SIZE= 10></P>
<P>Please enter your E-mail address: <INPUT TYPE="text" NAME="txtemail" SIZE= 10></P>
<P><INPUT TYPE="submit" NAME="submit" VALUE="Submit"></P>
</FORM>
<?php
$txtname = $_POST['txtname'];
$txtid = $_POST['txtid'];
$txtaddress = $_POST['txtaddress'];
$txtcell = $_POST['txtcell'];
$array = array(txtname=>$txtname, txtid=>$txtid, txtaddress=>$txtaddress,
txtcell=>$txtcell);
for each ($txtid as $key => $array){
echo "Your first name is ".$txtname.", id number is ".$txtid[$key].", your address is
".$txtaddress.", phone number is ".$txtcell.".";
}
?>
</BODY>
</HTML>
NEW UPDATE:
$txtname[0] = $_POST['txtname'];
$txtid[1] = $_POST['txtid'];
$txtaddress[2] = $_POST['txtaddress'];
$txtcell[3] = $_POST['txtcell'];
$txtmajor[4] = $_POST['txtmajor'];
$txtemail[5] = $_POST['txtemail'];
$student = array('txtname'=>$txtname, 'txtid'=>$txtid, 'txtaddress'=>$txtaddress,
'txtcell'=>$txtcell, 'txtmajor'=>$txtmajor, 'txtemail'=>$txtemail);
foreach ($student as $key => $txtname){
print_r ($student[$key]);
}
Array ( [0] => Amanda ) Array ( [1] => 12 ) Array ( [2] => 123 West Main Street ) Array ( [3] => 888-888-8888 ) Array ( [4] => CIS ) Array ( [5] => email#email.com )
I have updated the code. I cant get it to print out my array correctly.
I want it to be = Array( [0] => Amanda) [1]=>12 [2]=> 123 west main street...) what am i doing wrong?
The PHP manual for "foreach" says to do it like this:
foreach (array_expression as $key => $value)
But you have it like this:
for each ($txtid as $key => $array){ ... }
My guess is you want to replace that whole part with this:
foreach ($array as $key => $txtid ) {
echo "your $key is $txtid ";
}
I think it is not neccessary to to an array to get informations, you can just do like this :
<?php
// your form
$txtname = $_POST['txtname'];
$txtid = $_POST['txtid'];
$txtaddress = $_POST['txtaddress'];
$txtcell = $_POST['txtcell'];
echo "Your first name is ".$txtname.", id number is ".$txtid[$key].", your address is
".$txtaddress.", phone number is ".$txtcell.".";
?>
I'm trying to get a multidimensional array to store the info from three separate elements (caption, image, and subfolder). The three elements are descriptions from photos that individuals may upload onto my site. I've built an initial page that asks the visitor how many photos they intend to upload and from which country(an input type=select). Based upon their response on that initial form, the second page uses a loop to generate the appropriate number of , , and elements. Once the second form is submitted the intention is to upload the info to the server which it does. The second objective is to store that information inside the multidimensional array such as below in order to upload into a MySQL table. My dilemma is in getting the image names presumably from ($_FILES['image']['name']) to insert themselves into my multidimensional array. The captions '' insert themselves into the multidimensional array as does the country name ('name=subfolder']) but not the image names. I'd greatly appreciate anyone willing to help with this.
Thank you.
Array ( [caption] => Array ( [0] => Nice Simple Picture [1] Another Nice Simple Picture=> )
[image] => [subfolder] => Array ( [0] => Italy ) [upload] => UPLOAD )
Here's a bit of how I've attempted to go about this..
<?php
$file=$_FILES['image']['name'];
$expected = array('image','subfolder','caption');
foreach ($_POST as $key => $value) {
if (in_array ($key, $expected)) {
${$key} = mysql_real_escape_string($value); }}
$sql = "INSERT INTO images (file_name, country, caption)
VALUES ('$image', '$subfolder', '$caption')";
$result = mysql_query($sql) or die (my_sql_error()); }
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" id="form1" name="form1" method="POST"
enctype="multipart/form-data">
<?php
for ($i=0; $i<$imgnumb; $i++) {
echo "<input type=\"file\" name=\"image[".$i."]\" /> <input type=\"text\"
name=\"caption[".$i."]\" /><br />"; }
?>
<br />
<input value="<?php echo $file; ?>" name="image" type="hidden" />
<input value="<?php echo $location; ?>" name="subfolder" type="hidden" />
<input value="<?php echo $_POST['caption']; ?>" name="caption" type="hidden" />
<input type="submit" name="upload" id="next" value="UPLOAD" />
</form>