I wanted to make sure I am adding using these arrays correctly, could someone please go over my code and clarify. I have tried printing the array and nothing is displaying.
HTML
Start Date: <input type="text" name="start_date[]"/>
End Date: <input type="text" name="end_date[]"/>
Description:<textarea name="position[]"></textarea>
PHP
initializeArrays(); // Initialize arrays
$_SESSION['start_date_array'][] = $_GET['start_date[]']; // Add html input arrays to a session array.
$_SESSION['end_date_array'][] = $_GET['end_date[]'];
$_SESSION['position_array'][] = $_GET['position[]'];
$_SESSION['submit_employment_message'] = 'Thank you for the submission';
I want to set the array I am getting to my session array. Essentially I am expecting there to be multiple start dates. Being submitted to the PHP page. For example there could be multiple of start dates inputted. Please let me know if you need any clarification.
Thank you for the help!
I think you want:
$_SESSION['start_date_array'] = $_GET['start_date'];
$_SESSION['end_date_array'] = $_GET['end_date'];
$_SESSION['position_array'] = $_GET['position'];
Form fields that have [] appended to their name are assumed to be arrays
You can make foreach on $_GET and retrieve key=value
foreach ($_GET as $key => $value) {
$_SESSION[$key] = $value;
}
and retrieve the name of the sessions by the key of $_GET
Related
I'm not exactly sure how the logic would work on this. My brain is fried and i cant think clearly.
I am handling some POST data, and one of the fields in this array is a quantity string. I can read this string and determine if there are more than 1 widgets that need handled.
if($quantity <= 1){ //$_POST[widget1] }
Now say there are 4 widgets. The quantity field would reflect this number, but how would i loop through them and assign them to a new array themselves?
$_POST[widget1], $_POST[widget2], $_POST[widget3], $_POST[widget4]
How do i take that quantity number, and use it to grab that many and those specific named items from the post array, using some kind of wild card or prefix or something? I dont know if this is a for, or while, or what kind of operation. How do I loop through $_POST['widget*X*'], where X is my quantity number?
The end result is im looking to have an array structured like this:
$widgets[data1]
$widgets[data2]
$widgets[data3]
$widgets[data4]
Using a for loop, you can access the $_POST keys with a variable, as in $_POST["widget$i"]
$widgets = array();
for ($i=1; $i<=$quantity; $i++) {
// Append onto an array
$widgets[] = $_POST["widget$i"];
}
However, a better long-term solution would be to change the HTML form such that it passes an array back to PHP in the first place by adding [] to the form input's name attribute:
<input type='text' name='widgets[]' id='widget1' value='widget1' />
<input type='text' name='widgets[]' id='widget2' value='widget2' />
<input type='text' name='widgets[]' id='widget3' value='widget3' />
Accessed in PHP via $_POST['widgets'], already an array!
var_dump($_POST['widgets']);
Iterate over the number of items, at least over one (as you describe it):
$widgets = array();
foreach (range(1, max(1, $quantity)) as $item)
{
$name = sprintf('widget%d', $item);
$data = sprintf('data%d', $item);
$widget = $_POST[$name];
// do whatever you need to do with that $widget.
$widgets[$data] = $widget;
}
I am using values to be submitted to the next page through post method. The input type fields have dynamic names which are created like this name="fob-$id". Now when submitted through post, there are 4 - 5 variables such as fob-89, fob-29, fob-65 etc...
How can i assign these values to a new variable ???
NOTE: I know what numbers will be attached with the fob, so it will not be a problem, the only problem i am facing is about how to assign these values to a variable..
$fob=$_POST['fob-$id'];
Above code is not working.
Thanks
The best way would be to name your HTML fields so that they create an array when sent back to PHP:
echo "<input type='text' name='fob[$id]' />";
And then in PHP you can just iterate over $_POST['fob']:
foreach ($_POST['fob'] as $id => $value) {
// Do stuff
}
As per the comment updates, assuming $id is an integer gotten from the $_SESSION var, you can store it to an array:
$fob[$id] = $_POST['fob-' . $id];
You should use an array on the inputs name instead. Like this: name="fob[$id]"
Then you can simple do a foreach($_POST["fob"] as $id => $value) to get the values
I have a form that uses inputs to create and array. The inputs are not all required but at least one is.
<form method="post" action="process.php">
<input type="text" name="MAC[]" maxlength="12" />
<input type="text" name="MAC[]" maxlength="12" />
<input type="text" name="MAC[]" maxlength="12" />
<input type="text" name="MAC[]" maxlength="12" />
<input class="submitbg" type="submit" value="Register" name="submit"/>
</form>
Now on process.php I want to loop through the array remove two types of special characters : ; then make all upper case, and verify there are only 12 characters and then serialize the arrray.
$my_array = $_POST['MAC'];
foreach ($my_array as $val){
$val = strtoupper($val);
$val = str_replace(";","",$val);
$val = str_replace(":","",$val);
$val = trim($val);
if (strlen($val) != 12)){
$valid = false;
$error = "Your MAC address is not 12 characters long";
}
}
$mac_addresses = serialize($my_array);
// if valid is not false do something with the cleaned up array.
The questions:
Will my foreach loop save the updated values back into the array?
How to check to make sure there is at least one array value?
I am just not sure if my foreach loop updates and resaves the values each time
If you want to save the values you should change your loop so that it looks something like this:
foreach ($my_array as $idx => $val) {
...
$my_array[$idx] = $val;
}
Of course you could also save the proper value to a separate clean array which you will then use further on in your application.
I also have to check to make sure there is at least one entry.
In theory you do not have to check whether the array contains elements to use the array in a foreach. The thing you need to check though is whether the variable contains an array. Suppose the MAC[] field wasn't submitted to the server you would first get a warning (it might also be an error nowadays) because you are looking up some non-existent index in the array. Secondly you would get an error on your foreach as it works on arrays (or anything that is Traversable). You could fix this with the following check:
if (!empty($_POST['MAC'])) {
$my_array = $_POST['MAC'];
if (!is_array($my_array)) {
// throw some error.
}
}
Of course you would want to do this validation of your input in a more structured way by providing a validation framework which you can provide validation rules and some input and the validation framework will then handle the validation and most importantly the error messages for you.
Actually could also change the last if-statement to read:
if (!is_array($my_array) && !($my_array instanceof Traversable))
That is if you want to be sure $my_array contains something you can traverse over with foreach. The nasty bit is that the built-in array() isn't Traversable, nasty although understandable.
What's the question?
you can do str_replace(array(';',':'),'',$val);
It's usually better to trim before doing other processing on the same variable due to the overhead involved in processing data you will eventually cut
Consider using break on errors, if you halt execution on one error.
You're not really doing any updates to $my_array.
Consider doing:
foreach($my_array as &$val)
You pass by reference so all updates to $val happen to the actual array. Or:
foreach($my_array as $key=>$val){
$my_array[$key]=trim($my_array[$key]);
You can also try to create a new array for your sanitized data and then over-write your old array. It all depends on needs.
I'm also not understanding your question /problem.
But, looking at your code, you might get the feeling that in the end nothing has happened to your POSTed vars.
You're right! :-)
Your cleaned up array at the end of the script is exactly the original array.
You might want to achieve something like this: The clean array will contain cleaned values, if they consist of 12 characters.
$my_array = $_POST['MAC'];
$my_clean_array = $_POST['MAC'];
foreach ($my_array as $val) {
$val = strtoupper($val);
$val = str_replace(";","",$val);
$val = str_replace(":","",$val);
$val = trim($val);
if (strlen($val) != 12)) {
$valid = false;
$error = "Your MAC address is not 12 characters long";
}
else {
$my_clean_array[] = $val;
}
}
$mac_addresses = serialize($my_clean_array);
To check to see if you have at least one you should be able to use if(count($my_array) > 1)
I post some data over to another page from a form. It's a shopping cart, and the form that's being submitted is being generated on the page before depending on how many items are in the cart. For example, if there's only 1 items then we only have the field name 'item_name_1' which should store a value like "Sticker" and 'item_price_1' which stores the price of that item. But if someone has 5 items, we would need 'item_name_2', 'item_name_3', etc. to get the values for each item up to the fifth one.
What would be the best way to loop through those items to get the values?
Here's what I have, which obviously isn't working.
extract($_POST);
$x = 1; // Assuming there's always one item we're on this page, we set the variable to get into the loop
while(${'item_name_' .$x} != '') {
echo ${'item_name' .$x};
$x++;
}
I'm still relatively new to this kind of usage, so I'm not entirely how the best way to deal with it.
Thanks.
First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters
In addition, you don't have to use variable variable names (that sounds odd), instead:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
To ensure that you have only parameters beginning with 'item_name' you can check it like so:
$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
// do something
}
Use array-like fields:
<input name="name_for_the_items[]"/>
You can loop through the fields:
foreach($_POST['name_for_the_items'] as $item)
{
//do something with $item
}
If your post keys have to be parsed and the keys are sequences with data, you can try this:
Post data example: Storeitem|14=data14
foreach($_POST as $key => $value){
$key=Filterdata($key); $value=Filterdata($value);
echo($key."=".$value."<br>");
}
then you can use strpos to isolate the end of the key separating the number from the key.
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need
I have a PHP page that queries a DB to populate a form for the user to modify the data and submit.
The query returns a number of rows which contain 3 items:
ImageID
ImageName
ImageDescription
The PHP page titles each box in the form with a generic name and appends the ImageID to it. Ie:
ImageID_03
ImageName_34
ImageDescription_22
As it's unknown which images are going to have been retrieved from the DB then I can't know in advance what the name of the form entries will be.
The form deals with a large number of entries at the same time.
My backend PHP form processor that gets the data just sees it as one big array:
[imageid_2] => 2
[imagename_2] => _MG_0214
[imageid_10] => 10
[imagename_10] => _MG_0419
[imageid_39] => 39
[imagename_39] => _MG_0420
[imageid_22] => 22
[imagename_22] => Curly Fern
[imagedescription_2] => Wibble
[imagedescription_10] => Wobble
[imagedescription_39] => Fred
[imagedescription_22] => Sally
I've tried to do an array walk on it to split it into 3 arrays which set places but am stuck:
// define empty arrays
$imageidarray = array();
$imagenamearray = array();
$imagedescriptionarray = array();
// our function to call when we walk through the posted items array
function assignvars($entry, $key)
{
if (preg_match("/imageid/i", $key)) {
array_push($imageidarray, $entry);
} elseif (preg_match("/imagename/i", $key)) {
// echo " ImageName: $entry";
} elseif (preg_match("/imagedescription/i", $key)) {
// echo " ImageDescription: $entry";
}
}
array_walk($_POST, 'assignvars');
This fails with the error:
array_push(): First argument should be an array in...
Am I approaching this wrong?
Would it be possible to change the way the items are named on the form?
Current:
ImageID_03
ImageName_34
ImageDescription_22
Changed To:
ImageID[03]
ImageName[34]
ImageDescription[22]
This way it should come through the $_POST as three separate arrays meaning you can skip all that extra processing.
I hate to edit many rows at once. It's usability fault
If I go for it, I'd make it with such a form:
<form method="POST">
<input type="text" name="name[1]">
<input type="text" name="desc[1]">
<input type="text" name="name[2]">
<input type="text" name="desc[2]">
...etc
</form>
So, I'd have 2 arrays, $_POST['name'] and $_POST['desc'] where id used as a key
In your case I wouldn't use array_walk as it's just a syntax sugar, and make it with foreach to have full contorol over data processing.
I think you need
global $imageidarray;
to access a global array inside a function.
Something like this would work as well, assuming your three form fields are always submitted together:
$ids = preg_grep('/^imageid_(\d+)$/', array_keys($_POST)); // $ids now contains only the imageid_* keys
foreach($ids as $id) {
$id = substr($ids, 8); // now contains the numeric id of the field
echo $id, ": ", $_POST["imageid_$id"], "\n";
}
Not as efficient as using the array notation in the form names, but allows you to trivially extract just the ID numbers from one of the field names and then use it to access the other matching fields as well.