Unable to access values from multiple html checkboxes - php

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){
...
}

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

how to save multiple input fields value in mysql with codeigniter

I have a form having 6 fields with same nameLike - feature[],
I want to save multiple input fields value into mysql 1 column in JSON format:
<form method="post" action="<?php echo base_url();?>product/save/">
<input type="text" class="form-control" name="feature[]" placeholder="fetaure 1">
<input type="text" class="form-control" name="feature[]" placeholder="fetaure 2">
<input type="text" class="form-control" name="feature[]" placeholder="fetaure 3">
<input type="text" class="form-control" name="feature[]" placeholder="fetaure 4">
<?php ?>
I have column feature in mysql table, i want to save input field value into feature column as json data. i am using codeigniter 3.
ex for codeignitor
function save()
{
$feature = $this->input->post('feature');
$json = json_encode($feature);
$this->Your_model_Name->save($json);
}
You simply need to get the INPUTS based on the form method. Save the inputs in a variable based on form method post/get.
POST:
$features=$_POST["feature"];
GET:
$features=$_GET["feature"];
$features will be a PHP Array and you can use json_encode() to encode the PHP Array to JSON String. Like this,
$features_json=json_encode($features);
Now use this variable $features_json to save JSON String in MySQL Database.
Your JSON String after encoding will look like this: http://json-parser.com/67c07feb
Since it is an array, you need a foreach loop. your function must look like this
Controller
function save()
{
foreach($this->input->post('feature') as $f)
{
$f = trim($f);
$data = json_encode($f);
$this->YOUR_MODEL->insert_to_table($data);
}
}
Model
function insert_to_table($data)
{
$this->db->insert('table_name',$data);
}
This way, you post every input you have
hope this helps
controller (product)
function save() {
$features = $this->input->post('feature');
$feature_json = json_encode($features);
//send to model
$this->load->model('your_model');
$this->your_model->insert($feature_json);
}
model
function insert($feature_json) {
$data = array(
'features' => $feature_json
);
$this->db->insert($data);
}
update
Add trim and xss clean using form validation
$this->form_validation->set_rules('feature[]',"Feature", "trim|xss_clean");

How to store selected multiple checkbox values in an array in php?

<input type="checkbox"name="travel[]" value="bus"/>
<input type="checkbox"name="travel[]" value="train"/>
<input type="checkbox"name="travel[]" value="plane"/>
foreach($_POST['travel']as $selected)
var select[]=$selected;
If the user selects all the three checkboxes, I have to store them in an array and send it to mail as I dont have a data base. So how should I store them in an array?
foreach($_POST['travel']as $selected)
var select[]=$selected;
The above code is returning only last selected check box
And how should I pass it and display it on the mail?
Instead of
foreach($_POST['travel']as $selected)
var select[]=$selected;
update it to
$select = array();
foreach($_POST['travel'] as $key => $selected){
$select[$key]=$selected;
}
Instead of using foreach simply use $select = implode(',',$_POST['travel']);
Because every time you are defining a new array, by var select[]=$selected;.
Change it it $select[]=$selected;
please give different names as below.
after posting data using foreach loop you will get all selected options
<input type="checkbox" name="travel1[]" value="bus"/>
<input type="checkbox" name="travel2[]" value="train"/>
<input type="checkbox" name="travel3[]" value="plane"/>

Array to String Conversion error in Codeigniter

Well I am Stuck some where here in Array conversion:
My Controller:
$username = $this->input->post('FirstName');
$countryval= $this->input->post('country');
var_dump($countryval);
My View:
<input type="text" name="FirstName" id="Name" >
<?php
foreach ($countryDetails as $row )
{
echo '<input id="country" type="checkbox" name="country[]" class="unique" value="'.$row->country_id.'">'.$row->country_name.'<br/>';
}
?>
<script>
$('input.unique').click(function() {
$('input.unique:checked').not(this).removeAttr('checked');
});
</script>
I am getting the value from checkbox in an array and I need to pass that value as a string further.
I am not able to convert value from array to string i.e if I var_dump($countryval) I get value in array ! Please Help. Thank you
That is because you have used "country[]" as the name in input field
Please try this incase you need a single value to be returned (Edit made here coz I put type="checkbox" instead of "radio".. I have corrected it) Trust radios for single values.
echo '<input id="country" type="radio" name="country" class="unique" value="'.$row->country_id.'">'.$row->country_name.'<br/>';
hope that helps
You need "country[ ]" as name only if it has multiple values. Eg., For a multiple select
<select name="country[]" multiple>
<option></option> <!-- Your options go here-->
</select>
You can use input-checkbox too.. But with your question, I believe you need just a single value to be returned.
Ok.. Now From Your comments I kind of get what you want. Here is my suggestion
1) When you are having multiple checkboxes with the same name, the values are sent as an array.
2) If you would need a single value at a time and definitely need a checkbox, You can make a radio look like a checkbox like this.
3) If you really want to proceed with your javascript allowing only one checkbox at a time, you can do this.
// Load the 'array' helper
$this->load->helper('array');
// Use the 'element' function to return an element from the array
$countryval = element('0', $this->input->post('country')); //should work
Have a try..!!

How to get the values for a series of checkboxes in Laravel 4 controller (if checked)

I would like to get the values for a series of checkboxes I have set up in a Laravel 4 form. Here is the code in the view setting up the checkboxes:
#foreach ($friends as $friend)
<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}">
#endforeach
In my controller, I would like to get the values for the checked boxes and put them in an array. I am not exactly sure how to do this, but I assume it is something like:
array[];
foreach($friend as $x)
if (isset(Input::get('friend')) {
array[] = Input::get('friend');
}
endforeach
Could you provide me with a solution to do this? Thank you.
EDIT:
This is what I have in the controller:
public function describe_favorite() {
$fan = Fan::find(Auth::user()->id);
$fan->favorite_venue = Input::get('venue');
$fan->favorite_experience = Input::get('experience');
$friends_checked = Input::get('friend[]');
print_r($friends_checked);
if(is_array($friends_checked))
{
$fan->experience_friends = 5;
}
$fan->save();
return Redirect::to('fans/home');
}
It is not going through the "if" loop. How do I see the output of the print_r to see what's in the $friends_checked variable?
If checkboxes are related then you should use [] in the name attribute.
#foreach ($friends as $friend)
<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}">
#endforeach
$friends_checked = Input::get('friend');
if(is_array($friends_checked))
{
// do stuff with checked friends
}
The array friend must have a key . If there is $friend->id you could try something like this.
#foreach ($friends as $friend)
<input tabindex="1" type="checkbox" name="friend[{{$friend->id}}]" id="{{$friend}}">
#endforeach
Using name="friend[]" in the form field creates an array named friend that is passed to the server, as opposed to name="friend" which passes a string value to the server.

Categories