I need some help please. I need to create a drop down list and then when the option is submitted a php script must run. The complication is I can't hard code any of the values. I need it to be 'dynamically created'
config.php
$number_Of_Option="3"
$Option_One_Name="Cars"
$Option_One_Year="2000"
$Option_One_Colour="Blue"
$Option_Two_Name="Houses"
$Option_Two_Year="2003"
$Option_Two_Colour="Pink"
$Option_Three_Name="Bikes"
$Option_Three_Year="1990"
$Option_Three_Colour="Orange"
Now I need the drop down to be made with the name in the drop down to be "Cars", "Houses", "Bikes" but they must be variable based so if I change "Cars" it will change.
Then when the option is submitted (Option Two in this case) I need $Option_Two_Year and $Option_Two_Colour to be passed to a script where these two variables are the variables in the script. So the script is always the same however if drop down one is selected then it uses variables 1 if 2 then it uses variables 2 etc. I also need to it work for an infinite number of options so at any time I can got into the config.php and add another option with its own variables. It can use arrays and jquery if that's easier or necessary.
Thanks
Make an external file, eg. options.php, with this code:
$options = array();
$options["cars"] = array("2000","blue");
$options["houses"] = array("2003","pink");
$options["bikes"] = array("1990","orange");
Include this file in both the form page, and the parse script, using include("options.php");
In the form page, do:
include("options.php");
echo '<select name="option">';
foreach($options as $name => $values)
{ echo '<option value="' .$name .'">' .$name .'</option>';
}
echo '</select>';
In the parse script, do:
include("options.php");
$chosenValue = $_POST['option'];
list($year,$colour) = $options[$chosenValue];
Now $year and $colour will contain the year and colour for the option with the chosen name.
You know they invented arrays for this? If you got a reasonably recent version of PHP (I think 1.0 or higher ;) ), you could store this data like:
$options = array(
'Cars' => array('Year'=>'2000', 'Colour'=>'Blue'),
'Houses' => array('Year'=>'2003', 'Colour'=>'Pink'),
'Bikes' => array('Year'=>'1990', 'Colour'=>'Orange'));
Then you could get the selected option, and find the matching values by that option:
$option = $_GET['option'];
if (array_key_exists($option, $options))
{
$selectedYear = $options[$option]['Year'];
$selectedColour = $options[$option]['Colour'];
// Process them.
}
If you don't want to (or are not allowed to) use arrays, you'll need to match every variable:
if ($option === $Option_One_Name)
{
$selectedYear = $Option_One_Year;
$selectedColour = $Option_One_Colour;
}
elseif ($option === $Option_Two_Name)
{
...
Of course, you can speed this up a little bit. You can make an array of numbers and get the matching variables by their names
$numbers = array('One', 'Two', 'Three');
foreach($numbers as $number)
{
$optionVar = 'Option_' . $number . '_Name';
if ($option === $$optionVar)
{
$yearVar = 'Option_' . $number . '_Year';
$selectedYear = $$yearVar;
...
}
}
That code is more complex, but it won't need to be expanded if you get more option. You only need to update the Numbers array.
But still, as you can see, it will be easier to use arrays.
Related
I will be getting some certain amount of data. I will get the number for which the for loop to be run.
For example
I get the number 3 and I will get three parameters like par1,par2 and par3 then how should I pass this par1 in the $_post
like
$i=$_POST["number"];
for($i=1;$i<=$n;$i++)
{
$par.$i = $_POST["par".$i];
}
Here I cant get the value from $_POST["par".$i];
As it is not able to get the variable inside the paramater of $_POST
Any help will be thankful
I suggest that you create a new array $par and there you will put by index all the par you will have like this:
$i=$_POST["number"];
$par = [];
for($i=1;$i<=$n;$i++)
{
$par[$i] = $_POST["par".$i];
}
After that if you want to go throw all pars you can simply use foreach like this:
foreach($par as $key => $value) {
// $key will be 1,2,3
// $value will be the value from $_POST["par" . $i]
}
The . is to concatenate two strings in PHP, and you can't create a new variable like you tried. If you want to have in $par1, $par2 and $par3 you can do like this:
${"par" . $i} = $_POST["par".$i];
But I don't recommend this way because it's more hard to handle.
One Way
According to your question.
<?php
$n = $_POST["number"];
$par = "par";
for($i=1; $i<=$n; $i++){
$par.$i = $_POST["par".$i];
}?>
Alternative Way
In this scenario,
For example I get the number 3 and I will get three parameters like
par1,par2 and par3 then how should I pass this par1 in the $_post.
Better, make 'par' input name as an array type as 'par[]' (<input type='text' name='par[]'>) in your file instead using par1, par2 .. par(n).
And, no need to worry in submit page.
<?php
$n = $_POST["number"];
for($i=1;$i<= $n;$i++){
$newPar = $_POST["par"][$i];
// Write here your logic to use how you want.
}
?>
I have a code like that:
session_start();
$user = $_GET['user'];
$mode = $_GET['mode'];
$id1 = $_GET['id1'];
$id2 = $_GET['id2'];
$id3 = $_GET['id3'];
$id4 = $_GET['id4'];
$id5 = $_GET['id5'];
$id6 = $_GET['id6'];
$id7 = $_GET['id7'];
$id8 = $_GET['id8'];
$dep= $mode;
switch ($dep)
{
case "3m":
$dep = "Text 1";
break;
case "all":
$dep = "More text";
break;
default:
$dep = "Text1";
}
There are more other cases. I think I will have more id's and cases soon. Is there a simpler way to get all id's from URL push them into PHP code for evaluating?
I have found a code foreach:
foreach($_GET as $key => $value) {
echo 'key is: <b>' . $key . '</b>, value is: <b>' .$value. '</b><br />';
}
And it gets all variables from URL, but how to change the code in order to have it like this:
$variable = $_GET['variable'];
Any help appreciated :)
Use arrays, that's exactly what they're for. Name the parameters in the URL like:
id[]=1&id[]=2&...
Then $_GET['id'] is an array which you can easily loop through.
Many ids means you're looking for an array of ids, not id1, id2, id3 etc. An array allows you to access them virtually the same way as $id[1], $id[2] etc, but without the headache of needing to herd hundreds of independent variables.
There's also no need to assign each value from $_GET into its own variable, you can use those values directly from $_GET. They're not getting any better by assigning them into individual variables.
Assuming I understood correctly and you want all GET variables to be actual variables you can use, there's a function extract to do that.
However, as noted in the documentation:
Do not use extract() on untrusted data, like user input (i.e. $_GET,
$_FILES, etc.). If you do, for example if you want to run old code
that relies on register_globals temporarily, make sure you use one of
the non-overwriting flags values such as EXTR_SKIP and be aware that
you should extract in the same order that's defined in variables_order
within the php.ini.
So basically you should not do this unless you have good reasons, and be careful if you do as to not overwrite any existing values.
However, if your alternative is to do this:
foreach($_GET as $key => $value) {
$$key=$value;
}
then extract is certainly better, as a) you can set it to not overwrite any existing variables, and b) you can have a prefix, so those imported variables can be distinguished. Like this:
extract ( $_GET, EXTR_SKIP);
For $user, $mode, $id which don't overwrite anything, or
extract ( $_GET, EXTR_PREFIX_ALL, 'user_input' );
for $user_input_mode, $user_input_user, $user_input_id etc.
function getIDs()
{
$ids = array();
if(isset($_GET['id']))
{
foreach($_GET['id'] as $key => $value)
{
$ids[$key] = $value;
}
}
return $ids;
}
If you can get your URL to send an array of id GET parameters to a PHP script you can just parse the $_GET['id'] array in the above function, assuming the URI looks like ?id[]=1&id[]=2&id[]=3
$ids = getIDs();
You can write
foreach($_GET as $key => $value) {
$$key=$value;
}
this will assign every key name as a varibale.
In an attempt to keep php code seperated from html as much as possible in my pages, I'm trying to create a function which can be used to populate list/drop down boxes on other pages.
Using msqli, I have queried my table "acc_vat_rates! and selected the two fields I am interested in, "vat_rate_id" and "vat_rate_name"
I then loop through the result and populate an array called $vatratearray, code below...
<?php
function vat_rates(){
$conn = new mysqli("192.168.1.81", "root", "", "cloudoneaccountsdb");
$queryvat = "SELECT vat_rate_id,vat_rate_name FROM acc_vat_rates ORDER BY vat_rate_id";
$resultsvat = $conn->query($queryvat);
//SET UP AN ARRAY NOW
$vateratearray = array();
while ($rowvat= $resultsvat->fetch_assoc())
$vatratearray[] = $rowvat['vat_rate_id']." "." ". $rowvat['vat_rate_name'];
//print_r($vateratearray);
foreach($vatratearray as $key => $value)
//echo "<p>{$value} <?br></p>";
echo '<option value="'.$value.'">'.$value.'</option>';
}
?>
This function is stored in a page called "global_functions.php to be included in other pages
All of the above works fine. I then use the function "function vat_rates() as the option value for a list box on an other page, however, this is where my problems begin. When the function populates a listbox it displays the record_id and the name alongside each other, this is ok but when I post the selected line, it also posts the "id" and the "name" which is not what I require. I only want the "id" to be posted for inclusion in the DB.
I've been at this for a fair while, so any help would be appreciated.
Thanks...
David
You could just change your while loop and remove the foreach:
while ($rowvat= $resultsvat->fetch_assoc()){
echo '<option value="'.$rowvat['vat_rate_id'].'">'.$rowvat['vat_rate_name'].'</option>';
}
Try this:
while ($rowvat= $resultsvat->fetch_assoc())
{
array_push($vatratearray,
array('vat_rate_id' => $rowvat['vat_rate_id'],
'vat_rate_name' => $rowvat['vat_rate_name']
));
}
foreach($vatratearray as $key => $value)
{
echo '<option value="'.$value['vat_rate_id'].'">'.$value['vat_rate_id'].' '$value['vat_rate_name'].'</option>';
}
You can improve this code a lot....you can even create the options inside the while loop; just like the other answer XD
Saludos ;)
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 />';
}
}