Automate assignment of multiple values from the $_POST variable - php

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.

Related

get id dynamic inside $_POST PHP

Is this the right way to get ID dynamic within $_POST?
if( isset( $_POST['episode_title '. $episode_ID .''] ) ){
$episode_title . $episode_ID = $_POST['episode_title '. $episode_ID .''];
}
using '. $episode_ID .' to get id dynamic.
If not, then does someone know how? thanks.
$posts = $_POST;
foreach( $posts as $key => $value)
if(preg_match('/episode_title (\d+)/', $post))
{
// rest...
}
}

Retrieve post array values

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 );
}
}
}

How to fetch URL variable array using $_REQUEST['variable name']

I am using a URL to fetch data stored/shown within URL. I get all the value of variable using $_REQUEST['v_name'] but if there is a array in URL how can i retrieve that value.
For Example:
WWW.example.com/rooms?&hid=213421&type=E
I got the value hid and type using
$hid=$_REQUEST['hid'];
but in URL like:
WWW.example.com/rooms?&rooms=2&rooms[0].adults=2&rooms[0].children=0&rooms[1].adults=2&rooms[1].children=0
how can i retrieve value of adults and children in each room.
please help.
Thanks in Advance
You could also try something like this, since most of your original $_REQUEST isn't really an array (because of the .s in between each key/value pair):
<?php
$original_string = rawurldecode($_SERVER["QUERY_STRING"]);
$original_string_split = preg_split('/&/', $original_string);
$rooms = array();
foreach ($original_string_split as $split_one) {
$splits_two[] = preg_split('/\./', $split_one);
}
foreach ($splits_two as $split_two) {
if (isset($split_two[0]) && isset($split_two[1])) {
$split_three = preg_split('/=/', $split_two[1]);
if (isset($split_three[0]) && isset($split_three[1])) {
$rooms[$split_two[0]][$split_three[0]] = $split_three[1];
}
}
}
// Print the output if you want:
print '<pre>' . print_r($rooms, 1) . '</pre>';
$valuse = $_GET;
foreach ($valuse as $key=>$value)
{
echo $key .'='. $value. '<br/>';
}

PHP pass variable to foreach loop from a mySQL result

I need to pass a variable to a foreach loop from a mySQL result.
So I have this code:
$GetClaim = "SELECT * FROM cR_Claimants WHERE memberID = '".$memberID."' AND ParentSubmission ='".$refNumb."'";
$resultGetClaim=mysql_query($GetClaim) or die("Error select claimants: ".mysql_error());
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
$name = $rowGetClaim['Name'];
$city = $rowGetClaim['city'];
$region = $rowGetClaim['region'];
}
Now I need to pass the variable to the foreach
foreach($name as $k=>$v) {
echo $city;
echo $region;
etc..
}
The above code does not work. I think I cannot pass a variable from a mySQL loop. The problem is also tat every row I get from the database should be related to the specific $name. So obvioiusly one $name will have its own $city etc..
How do I achieve this?
Please help
You are not retrieving an array with all returned records, you are retrieving an array which contains a single record.
To get the next name (the next record), you must make another call to mysql_fetch_array.
The code you present does that implicitly by assigning $rowGetClaim within a while conditional. A failed mysql_fetch_array call would return false, which would exit the while loop.
There is absolutely no need to use the for each as you presented. Just place the echo right after the assignment (e.g.
$region = $rowGetClaim['region'];
echo $region
Either out put directly fromt eh loop or build an array and then loop through it.
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
echo $rowGetClaim['Name'];
echo $rowGetClaim['city'];
echo $rowGetClaim['region'];
}
OR
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
foreach($rowGetClaim as $k => $v{
echo $v;
}
}
OR
$names = array();
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
$names[] = $rowGetClaim;
}
foreach($names as $data){
foreach($data as $k => $v) {
echo $v;
}
}

How do I get the key values from $_POST?

echo $_POST["name"]; //returns the value a user typed into the "name" field
I would like to be able to also return the text of the key. In this example, I want to return the text "name". Can I do this?
$_POST is just a normal associative array so you can also loop over the entire thing like this:
foreach($_POST as $key=>$value)
{
echo "$key=$value";
}
Check out the array_keys() function assuming this is PHP.
http://us2.php.net/array_keys
#Tim: there was a ) missing. so it should be:
while( list( $field, $value ) = each( $_POST )) {
echo "<p>" . $field . " = " . $value . "</p>\n";
}
while( list( $field, $value ) = each( $_POST )) {
echo "<p>" . $field . " = " . $value . "</p>\n";
}
array_keys($_POST)
Manual
foreach($_POST as $rvar)
{
$rvarkey=key($_POST)
$$rvarkey=mysql_real_escape_string($rvar);
}
it creates variables having the name of the request parameters which is pretty awesome.

Categories