Submitting a Multidimensional Array Via Post With PHP

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
echo '<table>';
foreach ( $_POST['diameters'] as $diam )
{
// here you have access to $diam['top'] and $diam['bottom']
echo '<tr>';
echo ' <td>', $diam['top'], '</td>';
echo ' <td>', $diam['bottom'], '</td>';
echo '</tr>';
}
echo '</table>';
}

Sending multi-dimensional array by POST

Since you don't have any special characters in date, it is better to give without a ':

 echo "<input type='hidden' name=\"fixtures[$i]['team-a-name']\" value='$team_a_name'>";
echo "<input type='hidden' name=\"fixtures[$i]['team-b-name']\" value='$team_b_name'>";
echo "<input type='hidden' name=\"fixtures[$i][date]\" value='$fixtDate'>";

Or change it to:

 echo "<input type='hidden' name=\"fixtures[$i][team-a-name]\" value='$team_a_name'>";
echo "<input type='hidden' name=\"fixtures[$i][team-b-name]\" value='$team_b_name'>";
echo "<input type='hidden' name=\"fixtures[$i][date]\" value='$fixtDate'>";

Always use var_dump($_POST) or print_r($_POST) to check what's happening in reality. :)

Submitting a multidimensional array with file input via POST with php

The error correctly states that there is no file key in your array at that level. Instead you should use the key from the foreach loop.

On the top of my head, it should be something like:

foreach ( $_POST['prod'] as $key => $value ) {
^^^^ this will be your numeric index
//some code here
if (isset($_FILES['prod']['name'][$key]['file']) ...

But you'd better do a var_dump($_FILES['prod']); to confirm that as I am not sure how php handles multi-level file upload arrays.

How do I pass multi-dimensional arrays through a form in PHP?

I passed the name from th inputs as the array;

<input type='checkbox' name='prod_matrix[".$ceprod_id."][".$ceparam_id."]'>

where $ceprod_id is the product ID and $ceparam_id is the parameter ID (the headers)

I then caught these using 2 foreach loops:

$prod_matrix = $_POST['prod_matrix'];
foreach($prod_matrix as $prodid => $product)
{
echo $prodid;
foreach ($product as $paramid => $value)
{
echo $paramid;
echo $value;
}
echo "<br>";
}

Where $value is the data entered into the field (checkboxes give a value of "on" if checked, and pass nothing at all if unchecked)

I then used this information to build the query.

How to get multidimensional array from FORM via post, ajax, php, jquery?

I am pretty sure that you will get an unwanted format by doing that.
I'd do it like:

<div>
<select name="car[1][color]" size="1">
<?php $opt = new CarOptions;?>
</select>
<textarea name="car[1][history]"></textarea>
</div>
<div>
<select name="car[2][color]" size="1">
<?php $opt = new CarOptions;?>
</select>
<textarea name="car[2][history]"></textarea>
</div>

I would also change some of your javascript form submit listener:

$('form.ajax2').on('submit', function(e) {
e.preventDefault(); //'return false' is deprecated according to jQuery documentation, use this instead.

var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = that.serialize(); //This will capture all form input values, no need to reinvent the wheel

$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$('.success').html(response);
}
});
});

In the server side (PHP):

print_r($_POST)

/**
Will print the following data:

array() {
car => array () {
1 => array() {
color => colorValue,
history => historyValue
},
2 => array() {
color => colorValue,
history => historyValue
}
}
}
*/

PHP Create Multidimensional Array From Form Data

You can do this two ways. Both are suitable. I think I would consider the second way more secure as it is done completely server side. I will demo both for you.

First way:

You are going to use a hidden input field and serialize an array. You will pass the serialized array back to your post array on submit via the hidden input field. The code will push the new post data onto the unserialized array that it got from the hidden input field.

Like so:

<?php

if(isset($_POST['submit']) && $_POST['submit']){

$array = unserialize(base64_decode($_POST['articles']));

$array['articles'][] = array(

'tax' => $_POST['tax'],
'price' => $_POST['price'],
'description' => $_POST['description']

);

$postData = base64_encode(serialize($array));

}

?>

<!DOCTYPE HTML>
<html>

<head>
<title>My Simple Form</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>

<body style="background-color:#b3ffff">

<div style="padding-left:500px; padding-top:200px">

<form action="" method="post" enctype="multipart/form-data">

Tax: <input type="text" name="tax" placeholder="tax" value=""><br>
Price: <input type="text" name="price" placeholder="price" value=""><br>
Description <input type="text" name="description" placeholder="description" value=""><br>
<input type="hidden" name="articles" value=" <?php echo $postData; ?> ">
<input type="submit" name="submit" value="Submit">

</form>

</div>

</body>

</html>


<?php

echo
'<pre>';
print_r($array);
echo
'</pre>';

//When you need to convert it to a json string then use this:
$jsonString = json_encode($array);

?>

The second way

This way does not use a hidden input field. Instead we are just going to pass the post data to a $_SESSION variable which will store the array in memory on the server side. Just make sure you delete the session variable when you decide to leave the page because it will always be there if you don't. What I mean by that is that if you reload the page at a later time, all the data from the first time you were on the page will still be there.

session_start();

if(isset($_POST['submit']) && $_POST['submit']){

$_SESSION['myData']['articles'][] = array(

'tax' => $_POST['tax'],
'price' => $_POST['price'],
'description' => $_POST['description']

);

}

?>

<!DOCTYPE HTML>
<html>

<head>
<title>My Simple Form</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>

<body style="background-color:#b3ffff">

<div style="padding-left:500px; padding-top:200px">

<form action="" method="post" enctype="multipart/form-data">

Tax: <input type="text" name="tax" placeholder="tax" value=""><br>
Price: <input type="text" name="price" placeholder="price" value=""><br>
Description <input type="text" name="description" placeholder="description" value=""><br>
<input type="submit" name="submit" value="Submit">

</form>

</div>

</body>

</html>


<?php

echo
'<pre>';
print_r($_SESSION['myData']);
echo
'</pre>';

Passing a multidimensional array through hidden input via POST

You just need to encode array to json and decode it on action page

echo '<input type="hidden" name="itemsArr" value="'.json_encode($itemsArr). '">';

And at your action Page just decode it

$itemsArr = json_decode($_POST['itemsArr'],true)

Turning off multidimensional arrays via POST in PHP

It's a little over the top, but if necessary you could manually parse the request body.

<?php
if(!empty($_POST) && $_SERVER['CONTENT_TYPE'] == 'application/x-www-form-urlencoded') {
$_post = array();
$queryString = file_get_contents('php://input'); // read the request body
$queryString = explode('&', $queryString); // since the request body is a query string, split it on '&'
// and you have key-value pairs, delimited by '='
foreach($queryString as $param) {
$params = explode('=', $param);
if(array_key_exists(0, $params)) {
$params[0] = urldecode($params[0]);
}
if(array_key_exists(1, $params)) {
$params[1] = urldecode($params[1]);
}
else {
$params[1] = urldecode('');
}
$_post[$params[0]] = $params[1];
}
$_POST = $_post;
}
?>


Related Topics



Leave a reply



Submit