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
Related
I'm very new with PHP/Mysql, but I'm trying to make movie database.
There's a form where people can put in info about the movies, and the send button stores it in my database. Then another web page displays the movie list.
The text input and dropdown selections were easy. What I'm really struggling with is the multiple checkbox part. After hours of struggling I finally learned about the php array and how I can store all the values from my checkboxes using implode. My code looks like this:
$genre = implode( ';' , $_POST['genre'] );
This saves all the selected genres in the database, seperated by ;
However, I need help in displaying this data on my html page the way I want:
First off, I want to retrieve the results in a html list, instead of a;b;c
Second, I want to change a;b;c etc to actual words - for example Horror, Action, Comedy. Can this be done?
Hope someone can help! Thanks!
EDIT:
A friend told me that the best way to handle multiple checkbox values is to store them in a different table (moviegenres) and use mapping. So I rearranged my database like this:
One table called 'movies' that has the columns 'movieID' and 'title', and one table called 'moviegenres' that has the columns 'movieID' and 'moviegenre'.
I can still save the title into 'title' in 'movies', but when I want to add a command for adding genre to the 'moviegenres' table, nothing works...
What is the simplest way to do this?
Do I need to different commands for inserting into two tables, or can I do everything in one command, using one variable?
You can take the data say
$genre = 'a:b:c';
and use
$genreArr = explode(';', $genre);
to get this as an array. where you can get the values like
$genreArr[0] = 'a';
$genreArr[1] = 'b';
then in php page, use this code:
echo '<ul>';
foreach($genreArr as $g)
{
echo '<li>'. $g.'</li>';
}
echo '</ul>';
Yes you can used the explode() function to get an array of database checkbox values like you have fetching from db a;b;c
$values = explode(';', $dbcheckboxes);
After this just display in html. If you want to display actual words then make one array of actual words like
$actual_words = array(a => 'Horror', b => 'Action', c => 'Comedy');
Just compare the above database values with actual words array keys and you will get it.
You can get data explode it and loop it to print those values in html.
$checkbox_values=explode(";","a;b;c");
$map=array("a"=>"Apple","b"=>"banana","c"=>"carrot");
foreach($checkbox_values as $value)
{
echo "<p>"+$map[$value]+"</p>";
}
This would be a solution for your question.But since creating a map variable wont be dynamic, it is better to store the display string as it is to database such as "apple;banana;carrot".
$genre = implode( ';' , $_POST['genre'] );
$array_values = explode(';', $genre);
foreach ($array_values as $values) {
echo $values.'<br>';
}
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
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've been working on trying to write a function that will grab the POST values of any given form submission, pop them into an array, loop through the array using trim, addslashes etcetera pass that value back to a variable where it can then be passed to a database.
Now the hurdle I have atm is getting all the input,textarea,select element data into an array upon form submission. code I have follows
$fields = array($_POST['1'], $_POST['2']);
$i = 0;
foreach ($fields as $field) {
$i++;
${'field'.$i } = trim(addslashes(strip_tags($field)));
echo "POST field info #". $i ." - ". ${'field'.$i }."<br />";
}
As you can see everything is fine here baring that the POST value names are still being in-putted statically, what I need is a way to get that POST data fed into a loop which dynamically calls the POST name using an increment variable and then pop all that data into the same array. Code I have tried follows.
for ($ii=0;$ii++;) {
foreach($_POST['$ii'] as $field) {
$fields = array($field);
}
}
$i = 0;
foreach ($fields as $field) {
$i++;
${'field'.$i } = trim(addslashes(strip_tags($field)));
echo "POST field info #". $i ." - ". ${'field'.$i }."<br />";
}
Now I know this wont work but I can sense I am relatively close, so I am wondering if any clever person can help me sort the last part out? I sadly am now going to sleep and wont be viewing this post for at least 9 hours, apologies.
Thanks in advance.
Dan.
$arrayOfPostValues = $_POST; // it already is an array
$arrayOfPostValues = array_map('strip_tags', $arrayOfPostValues);
$arrayOfPostValues = array_map('trim', $arrayOfPostValues);
Or, if you really, really want to use a loop:
foreach ($arrayOfPostValues as &$value) {
$value = trim(striptags($value));
}
I'd absolutely advise against the use of addslashes, it serves very little purpose. Use mysql_real_escape_string or prepared statements instead.
I'd also advise against breaking the vales out of the array into separate variables, it can only cause problems. If you really want to do it, there's the extract function, which does exactly that. But, again, don't do it. Arrays are the perfect way to handle this kind of data.
You need to assign values to $_POST[1] and $_POST[2] to begin with, I've done this for you but normally they would be populated from a form I assume?
I'm not sure why you want to do this sort of thing: ${'field'.$key}, but I've left that part as is as I assume you must have a reason.
Anyway I've modified your code a bit, see below.
$_POST['1'] = '<h1>variable 1</h1>';
$_POST['2'] = '<h2>variable 2</h2>';
foreach($_POST as $key => $value){
${'field'.$key} = trim(addslashes(strip_tags($value)));
echo "POST field info #". $key ." = ". ${'field'.$key}."<br />";
}
The above code outputs:
POST field info #1 = variable 1
POST field info #2 = variable 2
On a side note, using field names such as '1' and '2' is not very good. Try using something more descriptive but as I said above I assume you have a reason for doing this.
UPDATE:
You can still get this to work for any form even if you are using specific names for the form elements. I have added a few lines below as an example for you.
$_POST['email'] = 'example#example.com';
$_POST['password'] = 'hgbks78db';
$_POST['name'] = '';
foreach($_POST as $key => $value){
if($value==''){
echo 'POST field "'.$key . '" is empty<br />';
/* I added the name of the field that is empty to an error array
so you have a way of storing all blank fields */
$a_error[] = $key;
}
else{
echo 'POST field "'.$key . '" is not empty<br />';
}
}
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.