I have a form where the user can add all the additional fields that they need.
Note: I would like to find a way to organize the code more efficiently, I will explain it in detail later.
As it is structured in HTML, I have simplified it to make it easier to understand:
<form action="" method="post">
<h1>Products</h1>
<p>
<input type="text" name="product_name[]" value="Product #1">
<input type="text" name="product_sku[]" value="pro-001">
<input type="text" name="product_price[]" value="$12.00">
<input type="text" name="product_stock[]" value="10">
</p>
<p>
<input type="text" name="product_name[]" value="Product #2">
<input type="text" name="product_sku[]" value="pro-002">
<input type="text" name="product_price[]" value="$12.00">
<input type="text" name="product_stock[]" value="10">
</p>
<p><button type="submit">Add Product</button></p>
</form>
I need to process these received data, to later work with them more easily, for example adding it to the database. But I get the code this way, a structure that doesn't make things much easier for working with that data.
Array
(
[product_name] => Array
(
[0] => Product #1
[1] => Product #2
)
[product_sku] => Array
(
[0] => pro-001
[1] => pro-002
)
[product_price] => Array
(
[0] => $12.00
[1] => $12.00
)
[product_stock] => Array
(
[0] => 10
[1] => 10
)
)
I wish I could receive the code like this:
Array
(
[0] => Array
(
[product_name] => Product #1
[product_sku] => pro-001
[product_price] => $12.00
[product_stock] => 10
)
[1] => Array
(
[product_name] => Product #2
[product_sku] => pro-002
[product_price] => $12.00
[product_stock] => 10
)
)
I have achieved it in the following way, but I want to do it in a more optimal way.
if(isset($_POST) && !empty($_POST)) {
// Total products to add
$total_products = count($_POST["product_name"]);
// Products ordered
$products_created = [];
for ($i=0; $i <$total_products ; $i++) {
$products_created[$i] = array(
'product_name' => $_POST["product_name"][$i],
'product_sku' => $_POST["product_sku"][$i],
'product_price' => $_POST["product_price"][$i],
'product_stock' => $_POST["product_stock"][$i]
);
}
echo "<pre>"; print_r($_POST);
echo "<pre>"; print_r($products_created);
}
Complete example code:
<?php
if(isset($_POST) && !empty($_POST)) {
// Total products to add
$total_products = count($_POST["product_name"]);
// Products ordered
$products_created = [];
for ($i=0; $i <$total_products ; $i++) {
$products_created[$i] = array(
'product_name' => $_POST["product_name"][$i],
'product_sku' => $_POST["product_sku"][$i],
'product_price' => $_POST["product_price"][$i],
'product_stock' => $_POST["product_stock"][$i]
);
}
echo "<pre>"; print_r($_POST);
echo "<pre>"; print_r($products_created);
}
?>
<form action="" method="post">
<h1>Products</h1>
<p>
<input type="text" name="product_name[]" value="Product #1">
<input type="text" name="product_sku[]" value="pro-001">
<input type="text" name="product_price[]" value="$12.00">
<input type="text" name="product_stock[]" value="10">
</p>
<p>
<input type="text" name="product_name[]" value="Product #2">
<input type="text" name="product_sku[]" value="pro-002">
<input type="text" name="product_price[]" value="$12.00">
<input type="text" name="product_stock[]" value="10">
</p>
<p><button type="submit">Add Product</button></p>
</form>
Solution in PHP
You could use a transpose function, that will turn your $_POST data into the desired data structure:
function transpose($array) {
foreach ($array as $key => $values) {
foreach ($values as $i => $value) $result[$i][$key] = $value;
}
return $result;
}
call as:
$products_created = transpose($_POST);
Solution in HTML
You could get the desired structure directly in PHP $_POST, if you change your HTML to this:
<form action="" method="post">
<h1>Products</h1>
<p>
<input type="text" name="product[0][name]" value="Product #1">
<input type="text" name="product[0][sku]" value="pro-001">
<input type="text" name="product[0][price]" value="$12.00">
<input type="text" name="product[0][stock]" value="10">
</p>
<p>
<input type="text" name="product[1][name]" value="Product #2">
<input type="text" name="product[1][sku]" value="pro-002">
<input type="text" name="product[1][price]" value="$12.00">
<input type="text" name="product[1][stock]" value="10">
</p>
<p><button type="submit">Add Product</button></p>
</form>
You would need some logic to inject that sequential number in the first bracket pairs in the name attributes. Assuming that this HTML is produced by PHP, it would not be hard to do that. If your HTML is dynamic on the client side, where rows can be added without interaction with the server, then you'll need to do this (also) in JavaScript.
I suppose you'll have no problem in setting that up.
Related
am trying to create array with key by using html input
here's my html input
<form method="post" action="">
<input type="text" name="name[][you]" value="" />
<input type="text" name="name[][he]" value="" />
<input type="text" name="name[][she]" value="" />
<input type="text" name="name[][you]" value="" />
<input type="text" name="name[][he]" value="" />
<input type="text" name="name[][she]" value="" />
<button type="submit">go</button>
</form>
my outbut is
Array ( [0] => Array ( [you] => jhon ) [1] => Array ( [he] => joy ) [2] => Array ( [she] => sarah ) [3] => Array ( [you] => samm ) [4] => Array ( [he] => petter ) [5] => Array ( [she] => susan ) )
but i want the array to be like this
Array( [0]=> array ( [you] => jhon [he] => joy [she] => sarah )[1]=> array ( [you] => pitter [he] => tom [she] => suszan ) )
is there away to do that
try like this ==>
<form method="post" action="">
<input type="text" name="name[0][you]" value="" />
<input type="text" name="name[0][he]" value="" />
<input type="text" name="name[0][she]" value="" />
<input type="text" name="name[1][you]" value="" />
<input type="text" name="name[1][he]" value="" />
<input type="text" name="name[1][she]" value="" />
<button type="submit">go</button>
</form>
OR
<form method="post" action="">
<?php $n = 2; // how many interval you want
for ($i = 0; $i < $n; $i++) {
?>
<input type="text" name="name[<?php echo $i; ?>][you]" value="" />
<input type="text" name="name[<?php echo $i; ?>][he]" value="" />
<input type="text" name="name[<?php echo $i; ?>][she]" value="" />
<?php } ?>
</form>
If you want to output an array with two children then set the keys manually, name[0] for the first three inputs and name[1] for the last three.
Everytime you write name="[][key]" php increment automatic the key.
if you write syntax like [] php increment the index of array.
Small explation
For example:
If you write an array like this
$array[] = "msg1";
$array[] = "msg2";
$array[] = "msg3";
$array length will be 2 (3 elements because it starts from 0) and it is same as
$array[0] = "msg1";
$array[1] = "msg2";
$array[2] = "msg3";
This is different from above
$array[0] = "msg1";
$array[1] = "msg2";
$array[1] = "msg3";
This array will have only 1 length (2 elements only)
Solution of your question is :
<form method="post" action="">
<input type="text" name="name[0][you]" value="" />
<input type="text" name="name[0][he]" value="" />
<input type="text" name="name[0][she]" value="" />
<input type="text" name="name[1][you]" value="" />
<input type="text" name="name[1][he]" value="" />
<input type="text" name="name[1][she]" value="" />
<button type="submit">go</button>
</form>
I have created a HTML form where a user can enter his availability (which day of week). The form has a button to add new users so at the end I will have multiple DIVs for users, hence I have USER_DOW with two dimensions USER_DOW[][].
<div id="user1" class="user" >
<div class="name">
<label>Name</label>
<input type="text" name="USER_Name[]">
</div>
<div>
<label>Day of Week</label>
<select multiple id="USER_DOW" name="USER_DOW[][]" size='7'>
<option value="Mon">Monday</option>
<option value="Tue">Tuesday</option>
<option value="Wed">Wednesday</option>
<option value="Thu">Thursday</option>
<option value="Fri">Friday</option>
<option value="Sat">Saturday</option>
<option value="Sun">Sunday</option>
</select>
</div>
</div>
I'm having issues accessing the elements in the PHP
foreach($USER_Name as $a => $b){
echo $a+1;
echo $USER_Name[$a];
echo "Number of selected days for user " + count($USER_DOW);
foreach($USER_DOW as $c => $b){
echo $USER_DOW[$c][$a];
}
}
At the moment, if I add 2 users, one selecting Wed.& Sun. and the second only Mon., what I get is three days (count) for both users and on the first user all three are printed (Wed, Sun, Mon) while for the second nothing.
Any idea? Have I misunderstood the keys in the arrays?
The names of input elements of a form are passed as written, without any interpretation.
So, in this example:
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<?php if( count($_GET) ): ?>
<pre><?php var_dump($_GET); ?></pre>
<?php endif; ?>
/* FORM #1 */
<form action="test.php">
<input type="text" name="txt[0]" value="One">
<input type="text" name="txt[1]" value="Two">
<input type="submit" name="action" value="Test">
</form>
/* FORM #2 */
<form action="test.php">
<input type="text" name="txt[]" value="One">
<input type="text" name="txt[]" value="Two">
<input type="submit" name="action" value="Test">
</form>
/* FORM #3 */
<form action="test.php">
<input type="text" name="txt[][]" value="One">
<input type="text" name="txt[][]" value="Two">
<input type="submit" name="action" value="Test">
</form>
<?php
?>
</body>
</html>
The generated URLs are:
/* FORM #1 */ test.php?txt[0]=One&txt[1]=Two&action=Test
/* FORM #2 */ test.php?txt[]=One&txt[]=Two&action=Test
/* FORM #3 */ test.php?txt[][]=One&txt[][]=Two&action=Test
(rawurldecoded for clarity)
When process $_GET/$_POST variables, PHP try to interpreter it, so in the first and second forms, the result is the same:
Array
(
[txt] => Array
(
[0] => One
[1] => Two
)
[action] => Test
)
But, in form #3, the result is:
Array
(
[txt] => Array
(
[0] => Array
(
[0] => One
)
[1] => Array
(
[0] => Two
)
)
[action] => Test
)
because PHP increment first-level key, but not the deeper key.
If you expectation is to increment the deeper array, you have to specify first-level key in the form.
Something like:
<input type="text" name="txt[1][]" value="One">
<input type="text" name="txt[1][]" value="Two">
or, if code-generated, like:
<input type="text" name="txt[<?php echo $SomeVar; ?>][]" value="One">
<input type="text" name="txt[<?php echo $SomeVar; ?>][]" value="Two">
<?php
var_dump($_POST);
function do_form($index) {
?>
<div id="user<?= $index ?>" class="user" >
<div class="name">
<label>Name</label>
<input type="text" name="USER_Name[<?= $index ?>]">
</div>
<div>
<label>Day of Week</label>
<select multiple id="USER_DOW" name="USER_DOW[<?= $index ?>][]" size='7'>
<option value="Mon">Monday</option>
<option value="Tue">Tuesday</option>
<option value="Wed">Wednesday</option>
<option value="Thu">Thursday</option>
<option value="Fri">Friday</option>
<option value="Sat">Saturday</option>
<option value="Sun">Sunday</option>
</select>
</div>
</div>
<?php
}
?>
<form method="POST">
<?php do_form(1); do_form(2); ?>
<input type="submit">
</form>
Sample output after submit:
array (size=2)
'USER_Name' =>
array (size=2)
1 => string 'foo' (length=3)
2 => string 'bar' (length=3)
'USER_DOW' =>
array (size=2)
1 =>
array (size=1)
0 => string 'Mon' (length=3)
2 =>
array (size=2)
0 => string 'Mon' (length=3)
1 => string 'Tue' (length=3)
I have a problem with my cloned form:
The form has 4 inputs and I need to separate the variables and put them together by people.
My inputs:
<input type="text" name="fName[]">
<input type="text" name="lName[]">
<input type="number" name="age[]">
<input type="text" name="city[]">
My PHP:
$fNameArray = $_POST['fName'];
$lNameArray = $_POST['lName'];
$ageArray = $_POST['age'];
$cityArray = $_POST['city'];
I really do not understand how two-dimensional arrays work, to group people to complete the form, as in the following example:
first name: siddharta, last name: naranjo, age: 29, city: mexico
first name: xxxxx, last name: xxxxxx, age: xx, city: xxxx.
Some of these answers are wrong if I understand you.
First of all if you use the naming convention data[]fname then it will not group surely?
Secondly, the blank bracket will have it constantly move to a new array.
You will end up with a load of arrays with one element in them.
You will need to number or ID the arrays to keep them together.
<?php
if(isset($_POST['data'])){
$results = $_POST['data'];
echo "<pre>";
print_r($results);
echo "<pre>";
}
?>
<form action="" method="post">
<!-- User 1 -->
<input type="text" name="data[0][fName]" value="test 1">
<input type="text" name="data[0][lName]" value="test 1">
<input type="number" name="data[0][age]" value="21">
<input type="text" name="data[0][city]" value="test 1">
<br>
<!-- User 2 -->
<input type="text" name="data[1][fName]" value="test 2">
<input type="text" name="data[1][lName]" value="test 2">
<input type="number" name="data[1][age]" value="22">
<input type="text" name="data[1][city]" value="test 2">
<br>
<!-- User 3 -->
<input type="text" name="data[2][fName]" value="test 3">
<input type="text" name="data[2][lName]" value="test 3">
<input type="number" name="data[2][age]" value="23">
<input type="text" name="data[2][city]" value="test 3">
<br>
<input type="submit" value="Go">
</form>
This produces this:
Array
(
[0] => Array
(
[fName] => test 1
[lName] => test 1
[age] => 21
[city] => test 1
)
[1] => Array
(
[fName] => test 2
[lName] => test 2
[age] => 22
[city] => test 2
)
[2] => Array
(
[fName] => test 3
[lName] => test 3
[age] => 23
[city] => test 3
)
)
Which is what it looks like you want?
Your html is ok
If i understand you right take a look at this
<?php
if($_POST && isset($_POST['fName'])) {
$people = count($_POST['fName']);
for($i=0; $i<$people; $i++) {
echo "<p>first name: {$_POST['fName'][$i]}, last name: {$_POST['lName'][$i]} ...</p>";
}
}
Use keys for 2 dimensional array.
<input type="text" name="fName[0]">
<input type="text" name="lName[0]">
<input type="number" name="age[0]">
<input type="text" name="city[0]">
<input type="text" name="fName[1]">
<input type="text" name="lName[1]">
<input type="number" name="age[1]">
<input type="text" name="city[1]">
INSERT multiple records in MySQL with one PHP form.
Simple Form
<form action="process.php" method="post">
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<input name="Submit" type="submit" />
</form>
//process.php
<?php
// connect to the database
include('connect-db.php');
$cnt = count($_POST['bline_id']);
$cnt2 = count($_POST['flow']);
if ($cnt > 0 && $cnt == $cnt2) {
$insertArr = array();
for ($i=0; $i<$cnt; $i++) {
$insertArr[] = "('" . mysql_real_escape_string($_POST['bline_id'][$i]) . "', '" . mysql_real_escape_string($_POST['flow'][$i]) . "')";
}
$query = "INSERT INTO bltest (bline_id, flow) VALUES " . implode(", ", $insertArr);
mysql_query($query) or trigger_error("Insert failed: " . mysql_error());
}
echo("<pre>\n");
print_r($_POST);
echo("</pre>\n");
mysql_close($connection);
?>
Array results
Array
(
[bline_id] => Array
(
[0] => Array
(
[bline_id] => 1
)
[1] => Array
(
[bline_id] => 2
)
[2] => Array
(
[bline_id] => 3
)
[3] => Array
(
[bline_id] => 4
)
[4] => Array
(
[bline_id] => 5
)
)
[flow] => Array
(
[0] => Array
(
[flow] => 11
)
[1] => Array
(
[flow] => 22
)
[2] => Array
(
[flow] => 33
)
[3] => Array
(
[flow] => 44
)
[4] => Array
(
[flow] => 55
)
)
[Submit] => Submit Query
)
the INSERT result is of course 5 rows but no data inserted for $bline_id or $flow. But looking at the array, that is the correct data.
USE PDO or Mysqli instead, these extensions have the prepare option, so you need ony to pass the query once, and that use a while loop to change the data!
<?php
// pdo example
$sql = 'INSERT INTO `table` (field1, field2, field3) VALUES (:value1, :value2, :value3)';
// $dbh is pdo connection
$insertTable = $dbh->prepare($sql);
$countArray = count($array);
$i = 0;
while ($i < $countArray) {
$insertTable->bindParam(':value1', $array[1][$i], PDO::PARAM_INT); // if value is int
$insertTable->bindParam(':value2', $array[2][$i], PDO::PARAM_STR); // if value is str
$insertTable->bindParam(':value3', $array[3][$i], PDO::PARAM_STR);
$insertTable->execute();
$i++;
}
?>
Okay. Given what you've told me, here's the solution I've thought up. I'm not going to give you code; it defeats the point of you writing it.
I would have the user type in some values into the two input text fields "bline_id" and "flow".
When they hit the submit button, those values are added to an array in the PHP code.
The array is then serialized into a string, and stored as a session cookie.
As each value is inputted, you unserialize the cookie so it is converted into an array, add the new value into the array, and repeat.
When the user hit's another button, "Store in Database". This option will unserialize the cookie, loop through each element in the array, and store each value in the database.
Also bare in mind that you have two values, bline_id and flow. These can be stored in two arrays and stored as two cookies. All it means is you're doing this process for two different arrays instead of one.
Finally, you should be using the PDO Object. I've linked you to it with the "store" link. It is the recommended method.
OMG!!!! I finally got it! It was my stupid form!
corrected below-------
<form action="process.php" method="post">
<p><label>Beamline ID</label>
<input type="text" name="bline_id[]" value="<?php echo $bline_id; ?>" />
<label>Flow</label>
<input type="text" name="flow[]" value="<?php echo $flow; ?>" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[]" value="<?php echo $bline_id; ?>" />
<label>Flow</label>
<input type="text" name="flow[]" value="<?php echo $flow; ?>" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[]" value="<?php echo $bline_id; ?>"/>
<label>Flow</label>
<input type="text" name="flow[]" value="<?php echo $flow; ?>" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[]" value="<?php echo $bline_id; ?>" />
<label>Flow</label>
<input type="text" name="flow[]" value="<?php echo $flow; ?>" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[]" value="<?php echo $bline_id; ?>" />
<label>Flow</label>
<input type="text" name="flow[]" value="<?php echo $flow; ?>" />
</p>
<input name="Submit" type="submit" />
</form>
Each div with the class "row" is added upon request from the user, to be able to add multiple items at once. So now is the question how I'll collect all the forms in to an array that PHP can read (like JSON for instance). I'll guess that there's already some easy and effective way of doing this?
<div class="container">
<div class="row">
<input type="text" name="value1" id="textfield" />
<input type="text" name="value2" id="textfield" />
<input type="text" name="value3" id="textfield" />
</div>
</div>
Here's what I would like to achieve out of the shown example:
array(
array ('value1' => '',
'value2' => '',
'value3' => '')
);
Thanks!
Update:
The form will be handled with PHP and it would be super to be able to do something like a foreach loop on the specific container-div content.
Give each 'group' of inputs the same name, then add square brackets to the end
<div class="container">
<div class="row">
<input type="text" name="value1[]" id="textfield" />
<input type="text" name="value2[]" id="textfield" />
<input type="text" name="value3[]" id="textfield" />
</div>
<div class="row">
<input type="text" name="value1[]" id="textfield" />
<input type="text" name="value2[]" id="textfield" />
<input type="text" name="value3[]" id="textfield" />
</div>
</div>
When you post the form, your php $_POST variable will then contain arrays for value1, value2 and value2:
var_dump($_POST); // array('value1' = array(...
You can then iterate through to 'regroup' the rows within PHP (but first, i'd change the field names to field1 etc rather than value1):
$rows = array(); // set up an empty array to hold your rows
// loop through each POST var
foreach($_POST AS $key=>$field) {
if(is_array($field)) {
foreach($field AS $rowIndex=>$fieldValue) {
$rows[$rowIndex][$field] = $fieldValue; // put the value in a the array by row, field
}
}
}
var_dump($rows);
This would give:
array(
[0] => array(
'field1' => 'value1',
'field2' => 'value2',
'field3' => 'value3'
),
[1] => array(
'field1' => 'value1',
'field2' => 'value2',
'field3' => 'value3'
),
...
)
<div class="container">
<div class="row">
<input type="text" name="value[0][value1]" class="textfield" />
<input type="text" name="value[0][value2]" class="textfield" />
<input type="text" name="value[0][value3]" class="textfield" />
</div>
<div class="row">
<input type="text" name="value[1][value1]" class="textfield" />
<input type="text" name="value[1][value2]" class="textfield" />
<input type="text" name="value[1][value3]" class="textfield" />
</div>
</div>
Changed id to class as reusing the same id is invalid HTML.
To convert XML to JSON you can try with:
Services_Json from PEAR: http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp
the Zend_Json component of the Zend Framework: http://framework.zend.com/manual/en/zend.json.xml2json.html