I have a form that sends all the data with jQuery .serialize() In the form are four arrays qty[], etc it send the form data to a sendMail page and I want to get the posted data back out of the arrays.
I have tried:
$qty = $_POST['qty[]'];
foreach($qty as $value)
{
$qtyOut = $value . "<br>";
}
And tried this:
for($q=0;$q<=$qty;$q++)
{
$qtyOut = $q . "<br>";
}
Is this the correct approach?
You have [] within your $_POST variable - these aren't required. You should use:
$qty = $_POST['qty'];
Your code would then be:
$qty = $_POST['qty'];
foreach($qty as $value) {
$qtyOut = $value . "<br>";
}
php automatically detects $_POST and $_GET-arrays so you can juse:
<form method="post">
<input value="user1" name="qty[]" type="checkbox">
<input value="user2" name="qty[]" type="checkbox">
<input type="submit">
</form>
<?php
$qty = $_POST['qty'];
and $qty will by a php-Array. Now you can access it by:
if (is_array($qty))
{
for ($i=0;$i<size($qty);$i++)
{
print ($qty[$i]);
}
}
?>
if you are not sure about the format of the received data structure you can use:
print_r($_POST['qty']);
or even
print_r($_POST);
to see how it is stored.
My version of PHP 4.4.4 throws an error:
Fatal error: Call to undefined function: size()
I changed size to count and then the routine ran correctly.
<?php
$qty = $_POST['qty'];
if (is_array($qty)) {
for ($i=0;$i<count($qty);$i++)
{
print ($qty[$i]);
}
}
?>
try using filter_input() with filters FILTER_SANITIZE_SPECIAL_CHARS and FILTER_REQUIRE_ARRAY as shown
$qty=filter_input(INPUT_POST, 'qty',FILTER_SANITIZE_SPECIAL_CHARS,FILTER_REQUIRE_ARRAY);
then you can iterate through it nicely as
foreach($qty as $key=>$value){
echo $value . "<br>";
}
PHP handles nested arrays nicely
try:
foreach($_POST['qty'] as $qty){
echo $qty
}
I prefer foreach insted of for, because you do not need to heandle the size.
if( isset( $_POST['qty'] ) )
{
$qty = $_POST ['qty'] ;
if( is_array( $qty ) )
{
foreach ( $qty as $key => $value )
{
print( $value );
}
}
}
Related
I have tried this simple code to generate an array which will send and a form data in post method. what is the way of receiving this array in desired page? Here is the code:
$serial = 0;foreach ($results as $row) {$serial = $serial + 1;
Html:
<input class="float-lt" type="radio" value=""; ?>" name="question-<?php echo "{$serial}"; ?>[]"/>
<input class="float-lt" type="radio" value=""; ?>" name="question-<?php echo "{$serial}"; ?>[]"/>
$used_serials = $_POST['serials];
foreach( $used_serials AS &$serial ){
$key = 'question-'.$serial;
$wanted_serial_pack = $_POST[$key];
}
OR better use an multidimensional Array structure like:
name="question['serials'][$serial]"
Then you can loop over $_POST['serials]
PHP
$serial = 0;
$inputs = array();
foreach ($results as $row) {
$serial = $serial + 1;
$inputs[] = "<input name=\"question['keys']['{$serial}'][]\"/>";
}
template.php:
echo implode(' ',$inputs);
Submit.php
$results = $_POST['keys];
foreach($results as $serial_array){
var_dump($serial_array);
}
Something like this may help.
how can I keep post variables through all the functions in php class?
I'm accessing post variables in a array in function. But when I try to access those in another function it retrvies only the last element in array.
foreach ( $questionAry as $questionID )
{
$questionName = $this->htmlID_questionID . $questionID;
$question_answer = $_POST[$questionName];
$_SESSION['qusID'] = $questionID;
$_SESSION['qusanswer'] = $question_answer;
}
I want to access $questionID and $question_answer in another function. I tried to do it through session, but I can only access last value.
Your loop is wrong...these guys are getting overwritten on every iteration
$_SESSION['qusID'] = $questionID;
$_SESSION['qusanswer'] = $question_answer;
You need to use an indexed loop, something like so...
foreach ( $questionAry as $key => $questionID )
{
$questionName = $this->htmlID_questionID . $questionID;
$question_answer = $_POST[$questionName];
$_SESSION['qusID'][$key] = $questionID;
$_SESSION['qusanswer'][$key] = $question_answer;
}
EDIT: based on conversation below, try something like so.
function getvalues() {
$questions = array();
$jsonEncoded = ( get_magic_quotes_gpc() ) ? stripslashes($_POST[$this->htmlID_questionIDAry]) : $_POST[$this->htmlID_questionIDAry];
$jsonDecoded = json_decode($jsonEncoded);
$questionAry = explode(",",$jsonDecoded->list);
$instr = "";
foreach ( $questionAry as $key => $questionID ) {
$questions[$key]['name'] = $this->htmlID_questionID . $questionID;
$questions[$key]['answer'] = $_POST[$questionName];
}
return $questions;
}
$parsedQuestions = getvalues();
name_of_other_function($parsedQuestions);
function name_of_other_function($parsedQuestions){
print_r($parsedQuestions);
}
I have some forms in my page like :
<form method="get">
Enter Your Firstname :<input type="text" name="t1" />
Enter Your Lastname :<input type="text" name="t2" />
<input type="submit" name="sb" />
</form>
so users will fill this form and i want to have values of this form separated with comma
for example
John,Smith
James,Baker
so here is my php code
if ( isset ($_GET['sb']))
{
$t_array = array("t1","t2");
foreach ( $t_array as $key )
{
echo implode(',' , $_GET[$key]);
}
}
When i try to do this , i got this error :
Warning: implode() [<a href='function.implode'>function.implode</a>]: Invalid arguments passed in PATH on line 24
i don't know why i can't use implode in $_GET or $_POST
so how can i solve this problem ?
P.S : i want to use array and implode in my page , please don't write about other ways
There is an error in your logic.
here is sample code that might help you:
$t_array = array($_GET['t1'], $_GET['t2']);
$imploded = implode(',', $t_array);
echo $imploded;
This will work.
You're calling implode on a value, not an array. This code
echo implode(',' , $_GET[$key]);
calls it on $_GET[$key], which is a string.
You are trying for implode($_GET);.
What you need is something like below, you don't actually need implode for this:
if ( isset ($_GET['sb']))
{
$t_array = array("t1","t2");
$result = '';
foreach ( $t_array as $key )
{
if ($result != '') $result .= ',';
$result .= $_GET[$key];
}
}
You can't impode strings...
Try something like this:
if ( isset ($_GET['sb']))
{
$t_array = array("t1","t2");
$arr = array();
foreach ( $t_array as $key )
{
$arr[] = $_GET[$key];
}
echo implode(',' , $arr);
}
I need to loop through a post array and sumbit it.
#stuff 1
<input type="text" id="stuff" name="stuff[]" />
<input type="text" id="more_stuff" name="more_stuff[]" />
#stuff 2
<input type="text" id="stuff" name="stuff[]" />
<input type="text" id="more_stuff" name="more_stuff[]" />
But I don't know where to start.
This is how you would do it:
foreach( $_POST as $stuff ) {
if( is_array( $stuff ) ) {
foreach( $stuff as $thing ) {
echo $thing;
}
} else {
echo $stuff;
}
}
This looks after both variables and arrays passed in $_POST.
Likely, you'll also need the values of each form element, such as the value selected from a dropdown or checkbox.
foreach( $_POST as $stuff => $val ) {
if( is_array( $stuff ) ) {
foreach( $stuff as $thing) {
echo $thing;
}
} else {
echo $stuff;
echo $val;
}
}
for ($i = 0; $i < count($_POST['NAME']); $i++)
{
echo $_POST['NAME'][$i];
}
Or
foreach ($_POST['NAME'] as $value)
{
echo $value;
}
Replace NAME with element name eg stuff or more_stuff
I have adapted the accepted answer and converted it into a function that can do nth arrays and to include the keys of the array.
function LoopThrough($array) {
foreach($array as $key => $val) {
if (is_array($key))
LoopThrough($key);
else
echo "{$key} - {$val} <br>";
}
}
LoopThrough($_POST);
Hope it helps someone.
You can use array_walk_recursive and anonymous function, eg:
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
array_walk_recursive($fruits,function ($item, $key){
echo "$key holds $item <br/>\n";
});
follows this answer version:
array_walk_recursive($_POST,function ($item, $key){
echo "$key holds $item <br/>\n";
});
For some reason I lost my index names using the posted answers. Therefore I had to loop them like this:
foreach($_POST as $i => $stuff) {
var_dump($i);
var_dump($stuff);
echo "<br>";
}
I just wrote the following code:
<?php
$email = checkPost("email");
$username = checkPost("username");
$firstname = checkPost("firstname");
$lastname = checkPost("lastname");
$zipcode = checkPost("zipcode");
echo("EMAIL: ".$email." USERENAME: ".$username);
function checkPost($formData) {
if (isset($_POST[$formData])) {
return $_POST[$formData];
}
}
?>
What I'd like to do is eliminate all those calls to checkPost() at the top. This code below doesn't require any knowledge of the fields in the form that submits to it, it just loops through all of the fields and spits out their values.
<?php
// loop through every form field
while( list( $field, $value ) = each( $_POST )) {
// display values
if( is_array( $value )) {
// if checkbox (or other multiple value fields)
while( list( $arrayField, $arrayValue ) = each( $value ) {
echo "<p>" . $arrayValue . "</p>\n";
}
} else {
echo "<p>" . $value . "</p>\n";
}
}
?>
I want to modify this code such that variables like $email, etc would be created and assigned values on the fly. Like say you run this on a form that has "email" and "name". You won't have to give php a variable name $email or $name. It will just loop through and for "email" create and fill a variable named $email and so on and so forth.
Am I dreaming?
foreach ($_POST as $key=>$value) {
echo '<p>', htmlspecialchars($key), ' = ', htmlspecialchars($value), '</p>';
}
I think that's what you're looking for anyway. Basically, we just loop through all $_POST elements and display them. You can of course do whatever you need with them, within the loop.
You could use...
extract($_POST, EXTR_SKIP);
...but I don't recommend it. This will unpack the array's keys into the scope it is in. I've set it to not overwrite existing variables.
You should explicitly define your variables.