Matthew
Matthew

Reputation: 3946

PHP Post array of array

I would like to alter two different tables from an HTML post request to a server running PHP. Before, when I only wanted to alter one table, all the columns and values were put into the POST array, so I would have [colname1]=>val1, [colname2]=val2, etc. I would then loop through the POST to build the correct MySQL statement to run the query.

I've modified my code so that depending on what drop down box is selected, not only will the first table get modified, but another table (of the users choice) will get modified as well. So ideally I would like the POST variable in PHP to have an array of arrays. So in the end, it would be nice if the POST variable looked like this...

[mainTable][colnam1]=>val1 [colnam2]=>val2
[otherTable][colnam1]=>val1 [colnam2]=>val2

My current workaround is having to give the table name in front of the the form input name and then parsing it on the server, but I would rather be more flexible and not do it this way.

<input type="text" name="mainTable_colname">
<input type="text" name="otherTable_colname">

From my understanding of using forms and POST, only the named html form elements will be passed up into the post variable.

Does anyone know a better way of doing this?

Upvotes: 3

Views: 452

Answers (1)

nickb
nickb

Reputation: 59699

Specify the name attribute of your elements to be arrays, including the keys you want, and you'll get arrays in $_POST:

<input type="text" name="mainTable[colname]">
<input type="text" name="mainTable[colname2]">
<input type="text" name="otherTable[colname]">

A var_dump( $_POST['mainTable']); would yield something similar to:

array( 'colname' => 1, 'colname2' => 1);

Upvotes: 4

Related Questions