Looping over an array of inputs with the same name - php

I'm making a todo list and I've got everything working except for this one thing. I need to loop over inputs that's been submitted via a form, these inputs have the same name so what I've done is storing them as an array. Now I need to loop over them so I can send them into the database one by one. Here's what I tried:
if (isset($_POST['submit'])) {
$labelValues = $_POST['labelValue[]'];
$i = 0;
while($i < sizeof($labelValues)) {
$stmt = $db->prepare("INSERT INTO tenta_table (text) VALUES (:text)");
$stmt->bindParam(':text', $labelValues[$i]);
$stmt->execute();
$i++;
}
}
HTML, the inputs are marked with red:
But it doesn't seem to work, it's not giving me any errors so I have nothing to go on. Where am I going wrong here?

Your $_POST['labelValue'] will already be an array if you have named your inputs correctly, something like <input type="text" name="labelValue[]" /> would create and array called labelValue in your POST.
From there you should be able to use your current code with one minor change
if (isset($_POST['submit'])) {
$labelValues = $_POST['labelValue'];
$i = 0;
while($i < sizeof($labelValues)) {
$stmt = $db->prepare("INSERT INTO tenta_table (text) VALUES (:text)");
$stmt->bindParam(':text', $labelValues[$i]);
$stmt->execute();
$i++;
}
}
Above I have change $labelValues to equal $_POST['lableValue'] rather than $_POST['labelValue[]']

In your case only the last input element will be available.
If you want multiple inputs with the same name use name="foo[]" for the input name attribute. $_POST will then contain an array for foo with all values from the input elements.
<form method="post">
<input name="a[]" value="foo"/>
<input name="a[]" value="bar"/>
<input name="a[]" value="baz"/>
<input type="submit" />
</form>
The reason why $_POST will only contain the last value if you don't use [] is because PHP will basically just explode and foreach over the raw query string to populate $_POST. When it encounters a name/value pair that already exists, it will overwrite the previous one.
However, you can still access the raw query string like this:
$rawQueryString = file_get_contents('php://input'))
Assuming you have a form like this:
<form method="post">
<input type="hidden" name="a" value="foo"/>
<input type="hidden" name="a" value="bar"/>
<input type="hidden" name="a" value="baz"/>
<input type="submit" />
</form>
the $rawQueryString will then contain a=foo&a=bar&a=baz.
You can then use your own logic to parse this into an array. A naive approach would be
$post = array();
foreach (explode('&', file_get_contents('php://input')) as $keyValuePair) {
list($key, $value) = explode('=', $keyValuePair);
$post[$key][] = $value;
}
which would then give you an array of arrays for each name in the query string.
or the best and simple approach for this
<form method="post">
<input name="a[0]" value="foo"/>
<input name="a[1]" value="bar"/>
<input name="a[2]" value="baz"/>
<input type="submit" />
</form>

You should replace
$labelValues = $_POST['labelValue[]'];
By
$labelValues = $_POST['labelValue'];

Not Sure, but as far as i remember it should be $labelValues = $_POST['labelValue']. I think your $labelValues is null and you don't even enter your loop. You should do a var_dump( $_POST ) to verify what you're working with.

Related

i want to be able to echo all the element in an array?

I pretty newbie to php and javascript but more i am curious about PHP. I want to add elements into a empty array every time i add a new element trough a input form, and after that i want those elements to be displayed in to the browser .The code i use is this
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="name"><br><br>
<input type="submit" name="submit" value="enter"><br><br>
</form>
<?php
if (isset($_POST['submit'])) {
$_SESSION['names']=array();
$names=$_SESSION['names'];
$name=$_POST['name'];
array_push($names,$name);
for($i=0;$i<count($names);$i++){
echo $names[$i];
}
};
How could i achieve to display every element inside the array that i add trough the input field in php?
You overwrite the value every time because you wipe out the array on every page load: $_SESSION['names']=array();. Instead check to see if that session variable exists (and is an array) first and, if it doesn't, then create it. Otherwise just append to that array.
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="name"><br><br>
<input type="submit" name="submit" value="enter"><br><br>
</form>
<?php
session_start();
if (isset($_POST['submit'])) {
if (!isset($_SESSION['names']) || !is_array($_SESSION['names'])) {
$_SESSION['names'] = array();
}
$name = $_POST['name'];
$_SESSION['names'][] = $name;
$num_names = count($_SESSION['names']);
for($i=0;$i<$num_names;$i++){
echo $_SESSION['names'][$i];
}
};

How to go through multiple array's and extract each value in each array using PHP?

Iam writing a program where i have a form with two fields and a 'PLUS BUTTON' upon clicking it two more fields will appear. By clicking PLUS Button again two more fields will generate and it continues as many times we click the PLUS BUTTON. Here's my program.
<form action="project_values/action_nowproject.php" method="post"enctype="multipart/form-data"><div id="item"><input type="text" name="add_qty" id="add_vender" class="ttexbox" required="required"><input type="text" name="add_name" class="ttexbox"><input onClick="addRowv(this.form);" type="button"style="cursor:pointer" class="addround" /></div></form>
in Javascript
<script type="text/javascript"> var rowNum = 0; function addRowv(frm) { rowNum ++;
var row = '<p id="rowNum'+rowNum+'"><span class="ftext">Item quantity:</span> <input type="text" name="m_name[]" value="'+frm.add_qty.value+'"><br> <span class="ftext">Item name: </span><input type="text" name="mi_name[]" value="'+frm.add_name.value+'"><br><br /> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRowsv').append(row); frm.add_qty.value = ''; frm.add_name.value = ''; } function removeRow(rnum) { jQuery('#rowNum'+rnum).remove(); } </script>
Now I have to fetch the values of extra fields appeared by clicking the plus button and send them to database.
How to fetch the values multiple array's genereated? heres my sql query insert statement.
$mp = "INSERT INTO pm_manr(name,item_nm)VALUES ('$add_qty','$item_name')";
$updata = mysql_query($mp);
How to get values in $add_qty,$item_name ? Some one pls help me.
Lets asume you have something like this:
line 1 <input name="foo[]" /> <input name="bar[]" />
line 2 <input name="foo[]" /> <input name="bar[]" />
line Y <input name="foo[]" /> <input name="bar[]" />
line Z <input name="foo[]" /> <input name="bar[]" />
You can loop trough them both by using the key from a foreach on the other values:
foreach($_POST['foo'] as $key =>$value){
echo $_POST['foo'][$key]; // the same as echo $value
echo $_POST['bar'][$key]; // the corresponding value of $_POST['bar']
// This is where you add your query
}
Use array_combine() which creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.
Try this:
$arr = array_combine($_POST['m_name'],$_POST['mi_name']); // combines both arrays
foreach($arr as $key => $value){
$mp = "INSERT INTO pm_manr(name,item_nm)VALUES ('$key','$value')";
$updata = mysql_query($mp);
}

storing multiple values in a single variable?

<form action="" method="post">
<input type="submit" name="foo" value="A" />
<input type="submit" name="foo" value="B" />
<input type="submit" name="foo" value="C" />
<input type="submit" name="foo" value="D" />
</form>
<?php
$letters = $_POST['foo'];
?>
each time form submit $letters will be filled with respective values. so $letters can be "A" or "B" or "C" etc.
is it possible store all submitted values at a time? say when I echo $letters it should give "ABCD" or "BCDBA" or whatever order form is submitted.
I think this can be done through $_SESSION but no Idea how...any ideas?
Hy
Try make the attribute name in each submit button: name="foo[]"
Then, in php, $_POST['foo'] contains an array with the value of each "foo[]"
echo implode('', $_POST['foo']);
You could use the session, so first: $_SESSION['letters']=array(); and then each post you can do $_SESSION['letters'][] = $_POST['foo']; and then you will have an ordered array.
This is how the top of your page will look:
session_start(); //important that this is first thing in the document
if ( !$_SESSION['letters'] ) {
$_SESSION['letters'] = array(); //create the session variable if it doesn't exist
}
if ( $_POST['foo'] ) { //if foo has been posted back
$_SESSION['letters'][] = $_POST['foo']; // the [] after the session variable means add to the array
}
You can use print_r $_SESSION['letters']; to output the array as a string, or you can use any of the many php array functions to manipulate the data.
Try this
$email_to = "";
$get= mysql_query("SELECT * FROM `newsletter`");
while ($row = mysql_fetch_array($get)) {
$email_to = $email_to.",".$row['mail'];
}
echo $email_to;

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

How to display all hidden field values passed from a form all at ONCE in PHP?

Let me explain.
Normally when hidden fields are passed from a form to the page specified in the action of the form, those hidden fields can be accessed on the processing page like so:
The Form:
<form action="process.php" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="hidden" name="loginTime" value="1:23PM" />
<input type="hidden" name="userIp" value="173.23.22.5" />
<input type="submit" name="submit" value="Submit" />
</form>
Processing Page (process.php):
<?php
if isset($_POST['submit']) {
echo $_POST['username'];
echo $_POST['loginTime'];
echo $_POST['userIp'];
}
?>
You see how I had to call the two hidden fields by name and individually. Is there any way I can call all hidden fields that are passed to a page from a form all at once despite what the field names of those are or how many there are?
In other words how do I make PHP do this:
// echo the contents of all hidden
fields here (if there were any)
EDIT
Additional info:
The form is designed in such a way (not the one above of course) that field names will be of the following sort:
product_name_1
product_quantity_1
product_price_1
product_name_2
product_quantity_2
product_price_2
and so incremented so on...
Depending on the user action there can be 3 hidden fields or thousands, there are no limits.
Make an array of valid hidden field names, then iterate through $_POST and if the $_POST field name is in the array of valid field names, echo them.
$valid = array('first_name', 'last_name');
foreach ( $_POST as $key => $value ) {
if ( in_array( $key, $valid ) ) {
echo $_POST[$key];
}
}
PHP does not care whether the field was hidden or not, HTTP doesn't tell PHP how it appeared on the website.
The closest thing I would come up with was saving all names of the hidden fields inside an array and echoing them all in a loop.
You can try the following:
<form action="process.php" method="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="hidden" name="group_hidden[loginTime]" value="1:23PM" />
<input type="hidden" name="group_hidden[userIp]" value="173.23.22.5" />
<input type="submit" name="submit" value="Submit" />
</form>
And then print it:
echo htmlspecialchars(print_r($_POST, true));
This might give you a clue about how to solve this.
there's no way to tell the type of the input built-in, so instead you'll need to come up with a way to identify the ones you want yourself. This can be done either by coming up with a special naming scheme, or by storing a list of the names of the hidden fields in another field. I'd recommend the former option, since you don't have the risk of losing data integrity somehow. Look at using array_filter to parse through the array to get the specially-named fields out.
Maybe, assuming that your hidden fields will be in sequence (i.e. 1,2,3 and not 1,2,4) following all of the end users' actions (adding and taking away fields), you could try something along the lines of
$i = 1;
while(isset($_POST["product_name_$i"]))
{
echo $_POST["product_name_$i"];
echo $_POST["product_price_$i"];
$i++;
}
Or something along those lines?

Categories