match array of posted values to an array of functions in php - php

I have a basic logic questions. My goal is to take the selected checkboxes from a form, submit them as an array and then match the values to an array of functions. Im trying to find a way of matching the selected input with the array of functions so i don't end up with pages of if {} elseif{} statements to cover an ever increasing number of options.
Here is an example of how i have my webform setup that contains a group of checkboxes. I am using "[]" to pass the selected values as an array.
webform:
<input type="checkbox" name="action[]" value="open" checked>open</input>
<input type="checkbox" name="action[]" value="close">close</input>
<input type="checkbox" name="action[]" value="lift">lift</input>
<input type="checkbox" name="action[]" value="drop">drop</input>
<input type="checkbox" name="action[]" value="destroy">destroy</input>
<input type="checkbox" name="action[]" value="create">create</input>
php post handler
$o = open();
$c = create();
$l = lift();
$d = drop();
$de = destroy();
$cr = create();
$mysvcs = array($o, $c, $l, $d, $de, $cr);
//stuck here
$action = $_POST['action'];
$postsvc = implode(",", $action );
$req = strstr($mysvcs, $postsvc);
?>
I sense that i'm probably going about this in completely the wrong way and would appreciate any guidance from the community.
Many thanks
-AussiedeviL

If you want to execute the checked functions the following code should work :
function open() {} //your open declaration
function close() {} //your close declaration
function lift() {} //your lift declaration
//all other declarations
foreach($_POST['action'] as $a){
$a();//execute matching function
}

Related

How to have checkbox items create a list

I am new to PHP and the project I am working on is a codeigniter php form writing back to a FileMaker database.
The checkboxes should be populating as a list field.
Here is my form
<input name="fieldname[]" value="value1"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value1
<input name="fieldname[]" value="value2"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value2
There are about 7 checkboxes.
I assume that I have to setup a foreach loop to get it to go thought to FileMaker's field, but unsure how to do that.
If I take away the array, the last one selected goes through to the layout.
Any help would be great.
Presumably, these values mirror a valueList back in FileMaker. If so, it's best to assign the valueList to a variable:
$values = $layout->getValueList('pizzaToppings');
And use that in your for loop:
foreach($values as $value)...
In your if(isset()) block, post a return-delimited array to FileMaker:
// value(s)!
if ($_POST['fieldname']) {
$valueArray = implode("\r", $_POST['fieldname']);
}
// pass the array to setField()
$record->setField('filemakerField', $valueArray);
I worked it out. To enter checked boxes into a return separated list:
View:
At the top of the section with the checkboxes
<?php $join->fieldname = explode("\n", $join->fieldname); ?>
// The actual input in the form
<input name="fieldnameXX[checkboxValue]" value="value" <?php echo (in_array('value', set_value('fieldname[value]', $join->fieldname)) ? ' checked="checked"': '')?> type="checkbox" class="form-check-input" > Value
Factory:
$fieldnameZZ = $data['fieldnameXX'];
$data['fieldnameXX'] = FALSE;
unset($data['fieldnameXX']);
$sacraments = implode("\n", $fieldnameZZ);
$data['fieldname'] = $fieldnameZZ;
I'm not sure if this is the best way to have done it, but it works.
$ids=implode(",", $_REQUEST["fieldname"]);
$result3=mysqli_query($dbh,'SELECT* FROM excel_tenant WHERE ID IN ("' .
$ids . '") AND
ManagerID = "'.$_SESSION["ManagerID"].'" ORDER BY ID DESC ') or
die(mysqli_error($dbh));

Unable to access values from multiple html checkboxes

I am trying to save the values from html checkboxes in a MySQL database table but I am not doing it right. I need your suggestions here.
This is my html
#foreach($sql as $sql)
<div class="form-group">
<label class="control-label mb-10" for="">{{$sql->name}}</label>
<div class="input-group">
<input type="hidden" name="resource[]" value="{{$sql->id}}">
<input type="checkbox" name="resources[]" value="c">Create
<input type="checkbox" name="resources[]" value="r">Read
<input type="checkbox" name="resources[]" value="u">Update
<input type="checkbox" name="resources[]" value="d">Delete
</div>
</div>
#endforeach
This is my controller where I am trying to save into a DB table
public function store(Request $request) {
foreach ($request->resource as $resource) {
# code...
foreach ($request->resources as $resources) {
$res[] = $resources;
$options = implode(',', $res); // Get selected options
$resource = $resource; // Get value of the resource
}
}
}
This does not work as it only shows just one 'selected checkbox field'.
Please what am I doing wrong?
Looking at your HTML code, it appears you're going to be looping over possibly more than one SQL statement to make the checkboxes. The server won't be able to tell these apart. You should change your checkbox names to be more like:
<input type="checkbox" name="resources[{{$sql->id}}][]" value="c">Create
<input type="checkbox" name="resources[{{$sql->id}}][]" value="r">Read
Then your PHP code could look something like this:
foreach ($request->input('resources') as $id => $resources) {
$options[$id] = implode(',', $resources);
}
Each SQL statement will be in the $options array keyed by the SQL id. The array value will be the checked checkboxes values separated by a comma.
print_r($options)
[
1 => "c,r,u,d",
2 => "c,r,d"
]
If you are trying to save the selected values separated by comma, for ex: if user has selected by c and d, then you are saving in database as c,d ?. if so then you can get all selected values in single line.
public function store(Request $request) {
// get all values separated by comma
$selectedValues = implode(",", $request->input('resources'));
// save values in database here
}
remember the your checkbox is an array !
for your understating better what sent to your controller just write
print_r($_POST);exit();
to see what arriving exactly after that write it in your framework method like :
foreach($_POST['resources'] as $resources){
...
}

get checkbox value in to a variable

This is my checkbox
<input name="interests2" type="checkbox" value="double-deep-racks" />
This is how I am trying to get that value in to a variable
$int = $_POST['interests2'];
Can you please tell me what i am doing wrong. I cant get the values I just get blank.
Try
$int = $_POST['interests2'];
If you are trying to set multiple checkboxes you can do something like,
// Your html
<input type="checkbox" name="interests[]" value="This is i">
<input type="checkbox" name="interests[]" value="Another i value">
// php
$email = "Further Information In: \n";
foreach($_POST['interests'] as $i)
$email .= $i . "\n";
The name of your checkbox is interests2. You must get the value by that name like this:
$int = $_POST['interests2'];
The name element must match what you are looking for. In your input field the name is interests2 but you are looking for interests (missing "2").
Also, you may possibly need to look in $_GET instead of $_POST, depending on the form or the AJAX method you are using (you didn't post that portion of your code).

How to pass multiple values to insert statement from dynamic number of html textboxs?

I am doing a project in which as per number getting by GET method, I display dynamic number of HTML Textbox for storing Multiple values. I am giving each textbox unique name+id in ascending manner starting from 1(Like textbox1,textbox2). Now I want that when I click on submit button, it should fire an insert statement which insert all textbox values at once. I know I can do by array, but my question is that how to get all textbox's value in an array and How to perform insert statement?
I have done following code:
Here is PHP Code for submit button:
$schedules = array();
if(isset($_POST['submit']))
{
for($d=1; $d<=$_GET['totalDay'] ;$d++)
{
array_push($schedules,$_POST['txtSchedule'.'$d']);
}
print_r($schedules);
}
Here is the html code:
<form method="post">
<table>
<tr>
<td>Day</td>
<td>Schedule</td>
</tr>
<?php
if(isset($_GET['tour_code']) and ($_GET['totalDay']!=1))
{
$tour_code = $_GET['tour_code'];
$total = $_GET['totalDay'];
$i=0;
do
{
$i=$i+1;
?>
<tr>
<td><?php echo $i;?></td>
<td>
<input name="txtSchedule<?php echo $i;?>" type="text" size="30"/>
</td>
</tr>
<?php
$start = date('Y-m-j',strtotime($start.'+1 days'));
}while($i!=$total);
}
?>
</table>
<input type="submit" name="submit" value="Add Tour Details" />
But I am getting an empty array.
Note: $total is coming through URLString's $GET method.
Below is the output of HTML:
Simplest thing first. You have an error, you can't use
array_push($schedules,$_POST['txtSchedule'.'$d']);
You must use DOUBLE QUOTES on the $d (single quotes won't evaluate d, it will literally read "txtSchedule$d" with a dollar sign, and not actually 0, 1,..., n)
array_push($schedules,$_POST['txtSchedule'."$d"]);
//or no quotes at all
array_push($schedules,$_POST['txtSchedule'.$d]);
(that may sovlve your problems)
But now let's get to how to make an array available to the $_POST object in the processing page via form naming conventions
You're not using array syntax, but you are oh-so close. In PHP, whatever is submitted needs to be of an expected format, and iterating txtSchedule0, txtSchedule1, ...txtScheduleN is not an Array(), but $_POST[] is an array that contains each (given what you've named your input fields, which is missing 1 small thing - square brackets).
What you need to do is be naming your inputs as an array is the array name followed by square brackets (arrayName[]), here is how you create an input array of the name txtSchedule (that way when you print_r($_POST['txtSchedule']) you get an Array())
<input name="txtSchedule[<?php echo $i;?>]" type="text" size="30"/>
I had the same issue when I started in PHP, you were forgetting the square brackets around [<?php echo $i;?>]
Just make sure that if you want to do an iteration over an array of inputs:
for($i=0; $i < count($_POST['txtSchedule']); $i++){
echo "They entered " . $_POST['txtSchedule'][$i] . " in the $i" . "th position";
}
... you have used the <input name="arrayName[$i]"> sytax, or even more simply <input name="arrayName[]"> for it to auto-magically generate an array on submit in the order the inputs were in the HTML page. The naming convention is so important, and since you have it wrong (you used arrayName0, arrayName1, ... arrayNameN instead of arrayName[0], arrayName[1], ... arrayName[n]), it will never be available to you as an array.
if i understand your question correctly you are trying to retrive user input from each textbox and save it in an array?
if so I would use jquery to select all textboxes and loop through them and retrive the value
If you are looking purely at the SQL syntax, then you can just append extra records to insert at the end of your query by providing more value sets:
INSERT INTO myTable (fieldName1, fieldName2) values ("Value1A", "Value1B"), ("Value2A", "Value2B")
If you looking at the PHP logic, then my first suggestion is to use the http POST method instead of GET. Then start with processing the $_POST fields:
$data= array();
foreach($_POST as $key => $value) {
if (preg_match('/^TextBox\d+$/', $key)) {
$data[] = $mysqli->real_escape_string($value);
}
}
The construct the SQL query based on the available data
if (count($data) > 0) {
$sql = 'INSERT INTO `myTable` VALUES("' . implode('"),("', $data).'")';
// log query
// execute query
// process query results
// redirect user to a thankyou page
header('Location: thankyou.php');
}
Note that the code assumes that you have a mysqli connection instance available at $mysqli
Not sure if this is what you are looking for but should give you at least a start..
String []ar=request.getParameterValues("name");
String cmd=request.getParameter("cmd");
if(cmd==null) cmd="";
if(cmd.equals("Submit")){
for(int i=0;i<ar.length;i++) {
insert logic;
<form method="post" action="page3.jsp">
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/> <input type="submit" value="Submit" name="cmd"/>
</form>
Orignal post http://www.daniweb.com/web-development/jsp/threads/197777/insert-dynamic-textbox-value-in-database

Get all variables sent with POST?

I need to insert all variables sent with post, they were checkboxes each representing a user.
If I use GET I get something like this:
?19=on&25=on&30=on
I need to insert the variables in the database.
How do I get all variables sent with POST? As an array or values separated with comas or something?
The variable $_POST is automatically populated.
Try var_dump($_POST); to see the contents.
You can access individual values like this: echo $_POST["name"];
This, of course, assumes your form is using the typical form encoding (i.e. enctype=”multipart/form-data”
If your post data is in another format (e.g. JSON or XML, you can do something like this:
$post = file_get_contents('php://input');
and $post will contain the raw data.
Assuming you're using the standard $_POST variable, you can test if a checkbox is checked like this:
if(isset($_POST['myCheckbox']) && $_POST['myCheckbox'] == 'Yes')
{
...
}
If you have an array of checkboxes (e.g.
<form action="myscript.php" method="post">
<input type="checkbox" name="myCheckbox[]" value="A" />val1<br />
<input type="checkbox" name="myCheckbox[]" value="B" />val2<br />
<input type="checkbox" name="myCheckbox[]" value="C" />val3<br />
<input type="checkbox" name="myCheckbox[]" value="D" />val4<br />
<input type="checkbox" name="myCheckbox[]" value="E" />val5
<input type="submit" name="Submit" value="Submit" />
</form>
Using [ ] in the checkbox name indicates that the selected values will be accessed by PHP script as an array. In this case $_POST['myCheckbox'] won't return a single string but will return an array consisting of all the values of the checkboxes that were checked.
For instance, if I checked all the boxes, $_POST['myCheckbox'] would be an array consisting of: {A, B, C, D, E}. Here's an example of how to retrieve the array of values and display them:
$myboxes = $_POST['myCheckbox'];
if(empty($myboxes))
{
echo("You didn't select any boxes.");
}
else
{
$i = count($myboxes);
echo("You selected $i box(es): <br>");
for($j = 0; $j < $i; $j++)
{
echo $myboxes[$j] . "<br>";
}
}
you should be able to access them from $_POST variable:
foreach ($_POST as $param_name => $param_val) {
echo "Param: $param_name; Value: $param_val<br />\n";
}
It is deprecated and not wished to access superglobals directly (since php 5.5 i think?)
Every modern IDE will tell you:
Do not Access Superglobals directly. Use some filter functions (e.g. filter_input)
For our solution, to get all request parameter, we have to use the method filter_input_array
To get all params from a input method use this:
$myGetArgs = filter_input_array(INPUT_GET);
$myPostArgs = filter_input_array(INPUT_POST);
$myServerArgs = filter_input_array(INPUT_SERVER);
$myCookieArgs = filter_input_array(INPUT_COOKIE);
...
Now you can use it in var_dump or your foreach-Loops
What not works is to access the $_REQUEST Superglobal with this method. It Allways returns NULL and that is correct.
If you need to get all Input params, comming over different methods, just merge them like in the following method:
function askForPostAndGetParams(){
return array_merge (
filter_input_array(INPUT_POST),
filter_input_array(INPUT_GET)
);
}
Edit: extended Version of this method (works also when one of the request methods are not set):
function askForRequestedArguments(){
$getArray = ($tmp = filter_input_array(INPUT_GET)) ? $tmp : Array();
$postArray = ($tmp = filter_input_array(INPUT_POST)) ? $tmp : Array();
$allRequests = array_merge($getArray, $postArray);
return $allRequests;
}
So, something like the $_POST array?
You can use http_build_query($_POST) to get them in a var=xxx&var2=yyy string again. Or just print_r($_POST) to see what's there.
Why not this, it's easy:
extract($_POST);
Using this u can get all post variable
print_r($_POST)

Categories