PHP - Getting data from hidden inputs with multiple square brackets - php

I have inherited some code which contains hidden inputs with multiple square brackets - example below:
<input name="myinput[1]['sausages'][2][]" type="hidden" />
<input name="myinput[1]['bacon'][1][]" type="hidden" />
<input name="myinput[2]['steak'][1][]" type="hidden" />
<input name="myinput[2]['mince'][2][]" type="hidden" />
The first value is referring to a 'type' field in the database, the second is the 'item' and the third is the 'order'
How can I extract this info using a for loop in php?

you can use a for-each to travel
foreach($myinput as $temp)
{
foreach($temp as $a)
{
echo $a;
}
echo "\n";
}
or if you want to read data using it's key use like this..,
foreach($myinput as $temp)
{
echo $temp['type'];
echo $temp['item'];
echo $temp['order'];
echo "\n";
}

Related

PHP - get uncertain number of fields

I have a problem with <form> in php .
i have uncertain number of fields (inputs) . it may be 1 or 100 input field .
Is there any function or class to get uncertain number of fields ?
Try that :
echo '<form>';
foreach ($data as $value) {
echo '<input name="field[]" value="',$value,'">';
}
echo '<input type="submit"></form>';
If you send that form, $_POST['field'] will be an indexed array in which every entry will correspond to one of the inputs.
$_POST would contain all the fields from the form on submit
print_r($_POST) will display them in an array for you
You can use an array name for the input fields in your form. For example, you can make an array of title fields by adding [] after the name:
<input type="text" name="title[]" />
<input type="text" name="title[]" />
<input type="text" name="title[]" />
Now in your PHP code, this value will be an array containing an amount of values equal to the number of fields with this name. The following code would print all titles on separate lines:
foreach ($_REQUEST['title'] as $value)
echo $value . "\n";
Just count the $_POST or $_GET what you use.
<?php
if(isset($_POST['submit'])){
echo "The total number of input fields is";
echo count($_POST); // include submit also
}
?>

How to get 2 value form input array into PHP array

I have an input :
<input type="text" name="input['.$opt_id.']">
and I can get $opt_id value on php side with :
foreach ($_POST['input'] AS $key => $value)
{
$opt_id=$value;
}
but I want to get second value like this :
<input type="text" name=input"['.$opt_id.']['.$lang_id.']">
How can I get $opt_id and $lang_id? I want to insert them on different columns in the database.
Assuming that you don't have 2 entries having the same opt_id and lang_id then you can use a single key instead of 2:
HTML:
<input type="text" name="input[<?php echo "{$opt_id}_{$lang_id}"; ?>]" />
PHP:
foreach ($_POST['input'] as $optIdAndLangId => $value) {
list($opt_id, $lang_id) = explode('_', $optIdAndLangId);
}
Within HTML markup you should insert PHP variables or any other PHP code in such way:
<input type="text" name="input[<?php echo $opt_id; ?>]">
...
<input type="text" name=input"[<?php echo $opt_id; ?>][<?php echo $lang_id; ?>]">
Try Like This
you can process the data with something like this:
<?php
foreach($_POST['input'] as $key => $opt_id){
foreach($opt_id as $ans=>$lang_id){
echo 'option id :'.$ans.' Lang Id : '.$lang_id;
}
}

Not able to get $_POST assigned to a variable PHP

I assume I have something stupid happening due to my lack of experience.
On a form on members.php I have:
$column = 0;
echo "<Form Name =member Method =POST ACTION = individual.php>";
echo "<table>";
echo "<tbody>";
while($row = $rs->fetch_assoc()) {
if ($column == 0) {
echo "<tr>";
}
echo '<td><INPUT TYPE = Submit NAME="'. $row['num'].'" VALUE ="'. $row['name'].'" id=Submit></td>';
$column++;
if ($column >= 5) {
echo "</tr>";
$row++;
$column=0;
}
}
echo "</tbody>";
echo "</table>";
echo "</form>";
On individual.php I have
print_r($_POST);
With the result being Array ( [16] => LUKE ) which is what is expected.
but when I try to
$name=$_POST['name'];
$num=$_POST['num'];
echo "<br>".$name." ".$num."<br>";
I do not get any results.
I mainly want to get $row['num'] but also did ['name'] to make sure I didn't transpose what I was trying to achieve.
I basically want to take what was selected on previous form and insert into a
select * from table where number=$num;
The name of your input fields are not num and name, instead, they are the values of these two keys in the array $row. That is why you are unable to retrieve these values on the backend.
Change your code to:
<input type="hidden" name="name" value="<?php echo $row['name']; ?>;">
<input type="hidden" name="num" value="<?php echo $row['num']; ?>;">
<input type="submit" value="Submit!" name="submit_form">
For obtain POST value for 'name' and 'num', you have to write:
<input type="text" name="name" value="<?php echo $row['name']; ?>">
<input type="text" name="num" value="<?php echo $row['num']; ?>">
type can be 'text' or 'hidden'
Enjoy your code!
If you want your form to return values that you can access using $_POST['name'] and $_POST['num'], you need to set name and num as input names on your form, and the appropriate values as the input values. If you don't want to add them as visible/editable values in your form, the usual way to do it is to use inputs of type hidden:
<form action="individual.php">
<input type="hidden" name="num" value="16" />
<input type="hidden" name="name" value="LUKE" />
<input type="submit" />
</form>
As it is, $_POST does contain the values that you're want, but they're not in an accessible format, because you've set 16 as an input name, so it turns into a key in the $_POST associative array. The form above will set num and name as keys in $_POST, and 16 and LUKE respectively as the values.

How do I access two arrays from a form simultaneously in php?

I receive two arrays from a form. In the .php file, I need to insert the values of each array into a column of the table.
- use the foreach loop to access the elements of one array and complete the insertion for only one column. When I do the same thing for the next array, I find that the corresponding first column elements are null in each row while for the first array, the corresponding second column elements are null. Is there anyway to avoid this and insert the array elements one after the other?
- I understand that foreach cannot be applied to two arrays so is there any other way I can access both the arrays simultaneously for insertion into a table?
Thanks.
You can use a foreach loop:
foreach($_POST['someField_1'] as $key => $value)
{
$fieldOne = $value;
$fieldTwo = $_POST['someField_2'][$key];
}
Obviously change the _POST variables to whatever you've named the fields.
As long as your field names are named something like: name="someField_1[]" and name="someField_2[]" You can use the foreach loop in this way.
EDIT
Take this HTML for your input form:
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
So that form allows you to enter forenames and surnames for up to 3 people. Each field has the exact same name: forename[] and surname[]
To retrieve each of the values, you would use this PHP:
foreach($_POST['forename'] as $key => $forename)
{
echo 'Forename: ' . $forename;
echo ' ';
echo 'Surname: ' . $_POST['surname'][$key] . '<br />';
}
This works because when you submit a field like forename[], with square brackets at the end, PHP will automatically convert this to an array. $key is a number which starts at 0, and goes on for however many fields there are.
PHP uses the $key to retrieve the correct fields. You could also write your HTML like this:
Forename: <input type="text" name="forename[0]"> Surname: <input type="text" name="surname[0]">
Forename: <input type="text" name="forename[1]"> Surname: <input type="text" name="surname[1]">
Forename: <input type="text" name="forename[2]"> Surname: <input type="text" name="surname[2]">
You see I've put a number between the square brackets? PHP will detect this and loop through the arrays.
You could even use a for loop:
for($i = 0; $i<count($_POST['forename']); $i++)
{
echo 'Forename: ' . $_POST['forename'][$i];
echo 'Surname: ' . $_POST['surname'][$i];
}

Searching for Array Key in $_POST, PHP

I am trying to add commenting like StackOverflow and Facebook uses to a site I'm building. Basically, each parent post will have its own child comments. I plan to implement the front-end with jQuery Ajax but I'm struggling with how to best tackle the PHP back-end.
Since having the same name and ID for each form field would cause validation errors (and then some, probably), I added the parent post's ID to each form field. Fields that will be passed are commentID, commentBody, commentAuthor - with the ID added they will be commentTitle-12, etc.
Since the $_POST array_key will be different each time a new post is processed, I need to trim off the -12 (or whatever the ID may be) from the $_POST key, leaving just commentTitle, commentBody, etc. and its associated value.
Example
$_POST['commentTitle-12']; //how it would be received after submission
$_POST['commentTitle']; //this is what I am aiming for
Many thanks
SOLUTION
Thanks to CFreak-
//Basic example, not actual script
<?php
if (array_key_exists("send", $_POST)) {
$title = $_POST['title'][0];
$body = $_POST['body'][0];
echo $title . ', ' . $body;
}
?>
<html>
<body>
<form name="test" id="test" method="post" action="">
<input type="text" name="title[]"/>
<input type="text" name="body[]"/>
<input type="submit" name="send" id="send"/>
</form>
</body>
</html>
Update 2
Oops, kind of forgot the whole point of it - unique names (although it's been established that 1) this isn't really necessary and 2) probably better, for this application, to do this using jQuery instead)
//Basic example, not actual script
<?php
if (array_key_exists("send", $_POST)) {
$id = $_POST['id'];
$title = $_POST['title'][$id];
$body = $_POST['body'][$id];
echo $title . ', ' . $body;
}
?>
<html>
<body>
<form name="test" id="test" method="post" action="">
<input type="text" name="title[<?php echo $row['id'];?>]"/>
<input type="text" name="body[<?php echo $row['id'];?>]"/>
<input type="hidden" name="id" value="<?php echo $row['id']; //the ID?>"/>
<input type="submit" name="send" id="send"/>
</form>
</body>
</html>
PHP has a little trick to get arrays or even multi-dimensional arrays out of an HTML form. In the HTML name your field like this:
<input type="text" name="commentTitle[12]" value="(whatever default value)" />
(you can use variables or whatever to put in the "12" if that's what you're doing, the key is the [ ] brackets.
Then in PHP you'll get:
$_POST['commentTitle'][12]
You could then just loop through the comments and grabbing each by the index ID.
You can also just leave it as empty square brackets in the HTML:
<input type="text" name="commentTitle[]" value="(whatever default value)" />
That will just make it an indexed array starting at 0, if you don't care what the actual ID value is.
Hope that helps.
You just have to iterate through $_POST and search for matching keys:
function extract_vars_from_post($arr) {
$result = array();
foreach ($arr as $key => $val) {
// $key looks like asdasd-12
if (preg_match('/([a-z]+)-\d+/', $key, $match)) {
$result[$match[1]] = $val;
} else {
$result[$key] = $val;
}
}
return $result;
}
Didn't test the code, though

Categories