Php add input field values in database - php

What the best way to add values of input files and save them later on in the database.
My input fields look like these:
<input type="checkbox" name="test[]" value="1">
<input type="checkbox" name="test[]" value="10">
<input type="checkbox" name="test[]" value="100">
<input type="checkbox" name="test[]" value="1000">
<input type="checkbox" name="test[]" value="10000">
<input type="checkbox" name="test[]" value="100000">
<input type="checkbox" name="test[]" value="1000000">
So if I check the first field and send the database saves 1 and if I check the first 3 the database should save 111(1+10+100) and so on...
Edit:
So I tried out your suggestion.
Printing out the array gives this:
array:1 [▼
"test" => array:3 [▼
0 => "1"
1 => "10"
2 => "100"
]
]
But if I array_sum that and print out the value I get a 0.

Try this
$sum = 0;
if(isset($_POST['test']) && is_array($_POST['test'])){
$sum = array_sum(array_map('intval', $_POST['test']));
}

Related

Laravel Collective checkbox element for laravel many-many relationship

i wanna use laravel collective for my input form,im using this to input datas for pivot table in laravel eloquent many-to-many,and i wanna use input data using checkbox element(hoby),the problem is idont know why we type at the first parameter of laravelCollective as string and way we have to type as array,anyone can explain me?in theory,thanks in advance for your help
<div class="form-check">
#if (count($list_hobi)>0)
#foreach ($list_hobi as $key => $value)
<div class="checkbox">
{{Form::checkbox('hobi[]',$key,null)}}
<label>{{$value}}</label>
</div>
#endforeach
#endif
</div>
Take for example these checkboxes:
<input type="checkbox" name="food" value="apple" /> 1
<input type="checkbox" name="food" value="pear" /> 2
<input type="checkbox" name="food" value="banana" /> 3
All three have the same name. When I check all three and submit the form and see what has been submitted with dd($request->input()), the output is:
"food" => "banana"
It appears only the last input with the same name is saved, even though I selected all three.
When I instead use food[]:
<input type="checkbox" name="food[]" value="apple" /> 1
<input type="checkbox" name="food[]" value="pear" /> 2
<input type="checkbox" name="food[]" value="banana" /> 3
the output is:
"food" => array:3 [▼
0 => "apple"
1 => "pear"
2 => "banana"
]

get the right result for inserting into the database - Laravel

Im trying to store data in this table:
newspaper_id
article_id
comment (string)
This is how my HTML looks like:
<div class="newspaper-options">
<input class="form-control" name="data[]" type="text">
<input type="checkbox" class="article-option" name="article_id[]" value="3"> Active
</div>
<div class="newspaper-options">
<input class="form-control" name="data[]" type="text">
<input type="checkbox" class="article-option" name="article_id[]" value="1"> Active
</div>
This is the result im getting back when i only fill in the second newspaper options and check it:
"comment" => array:2 [▼
0 => ""
1 => "option 2"
]
"article_id" => array:1 [▼
0 => "1"
]
The problem im having is how can i group the input values so i can store it inside my table. The value of my checkbox is that of the article_id. and the text field is used to fill the comment inside the database.
Any help with this would be greatly appreciated!
The information that is missing to correctly put that info into the database is the mapping of the array position to the article_id.
E.g. put
<input name="article[]" type="hidden" value="...">
in each <div class="newspaper-options">
Like so
<div class="newspaper-options">
<input name="article[]" type="hidden" value="3">
<input class="form-control" name="data[]" type="text">
<input type="checkbox" class="article-option" name="article_id[]" value="3"> Active
</div>
<div class="newspaper-options">
<input name="article[]" type="hidden" value="1">
<input class="form-control" name="data[]" type="text">
<input type="checkbox" class="article-option" name="article_id[]" value="1"> Active
</div>
Then in your Controller you can loop through Input::get('article'), check the active checkbox and add the comment.
E.g.
foreach(Input::get('article') as $pos => $article_id){
if(in_array($article_id, Input::get('article_id')){
add $article_id and Input::get('comment')[$pos] to DB
}
}
Apart from that you should get a better name for your article_id field, like "active" and change "data" to "comment".
If you could add the input fields with keys in the first place you could handle them more easily. I guess it is possible to do
<input class="form-control" name="data[3]" type="text">
<input type="checkbox" class="article-option" name="article_id[3]" value="3"> Active

comma seperated checkbox $_GET query request with jquery

Trying to create a search function using multiple checkboxes, but seem to be only finding information related to $_POST requests.
<input type="checkbox" name="fruit" value="1">
<input type="checkbox" name="fruit" value="2">
<input type="checkbox" name="fruit" value="3">
<input type="checkbox" name="fruit" value="4">
<input type="checkbox" name="fruit" value="5">
What is the best way to get the query to look like this
search?fruit=1,2,3,4
Is there a way to do this non ajax?
Just to clarify...
Each value represents a different fruit.
Originally I did this
search?apple=1&orange=1
As I added more checkboxes, the query seemed inefficient.
I know that I can add the checkboxes into the array using the $_POST method
<input type="checkbox" name="fruit[]" value="1">
<input type="checkbox" name="fruit[]" value="2">
As a few have suggested using this technique for a $_GET query would look something like this
search?fruit[]=1&fruit[]=2&fruit[]=5
So the question is really how to clean it up (comma seperated)
NOTE: As others have pointed out, it isn't necessary to pass a single parameter with a comma-separated value to end up with an array or a comma-separated value on the server. Frameworks like PHP can handle this with no JavaScript required. You can simply give each checkbox the same "name" attribute. That will cause multiple parameters with the same name to be passed to the server, which is just fine. In fact, it is the same result you would get if you used a <select multiptle="multiple"> element.
In PHP, if you use a name with square brackets at the end, like fruit[], you can then get an array on the server with:
$_GET['fruit']
And if you want a comma-separated value on the server, you can use:
implode(',', $_GET['fruit'])
But if you really want a single parameter with a comma-separated value, here is how you can do it:
You can use a form with a hidden input. Set the form's "method" to "get" and the hidden input's "name" to "fruit". Then add an event handler that sets the value of the hidden input to the comma-separated string when the form is submitted.
HTML:
<form id="fruitForm" action="search" method="get">
<input type="hidden" name="fruit" />
<label><input type="checkbox" value="1" />apple</label><br />
<label><input type="checkbox" value="2" />banana</label><br />
<label><input type="checkbox" value="3" />orange</label><br />
<label><input type="checkbox" value="4" />pineapple</label><br />
<label><input type="checkbox" value="5" />grapefruit</label><br />
<button type="submit">submit</button>
</form>
JQuery:
$('#fruitForm').submit(function() {
var fruits = $('#fruitForm').find('input:checkbox:checked').map(function() {
return $(this).val();
}).get().join(',');
$('#fruitForm').find('input[name=fruit]').val(fruits);
});
Note: The checkbox elements do not have "name" attributes, so they do not get included in the form submission.
jsfiddle
Use fruit[] as the input name
<input type="checkbox" name="fruit[]" value="1">
<input type="checkbox" name="fruit[]" value="2">
<input type="checkbox" name="fruit[]" value="3">
<input type="checkbox" name="fruit[]" value="4">
<input type="checkbox" name="fruit[]" value="5">
You will get the following:
echo "<pre>", print_r($_GET["fruit"], true);
Output
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Try this, Use checkbox name as fruit[]. In php get the fruit array and converted as string using implode()
<?php
echo $fruits = implode(",",$_GET['fruit']); //1,2,3,4,5
?>
<form>
<input type="checkbox" name="fruit[]" value="1">
<input type="checkbox" name="fruit[]" value="2">
<input type="checkbox" name="fruit[]" value="3">
<input type="checkbox" name="fruit[]" value="4">
<input type="checkbox" name="fruit[]" value="5">
<input type="submit">
</form>

How get value for unchecked checkbox in checkbox elements when form posted?

I have a form like below :
<form action="" method="post">
<input type="checkbox" id="status_1" name="status_1" value="1" />
<input type="checkbox" id="status_2" name="status_2" value="1" />
<input type="checkbox" id="status_3" name="status_3" value="1" />
</form>
When i check all checkbox and post the form, the result is like this:
Array ([status_3] => 1 [status_2] => 1 [status_1] => 1 )
Then i uncheck second checkbox and post the form, the result is like this:
Array ( [status_3] => 1 [status_1] => 1 )
Is it possible to make result like this below when i uncheck second checkbox :
Array ( [status_3] => 1 [status_2] => 0 [status_1] => 1 )
There are ideas to do it?
First way - hidden fields (disadvantage: the user can manipulate the value of the field (but one can manipulate the value of the checkbox too, so it's not really a problem, if you only expect 1 or 0))
<form action="" method="post">
<input type="hidden" name="status_1" value="0" />
<input type="checkbox" id="status_1" name="status_1" value="1" />
<input type="hidden" name="status_2" value="0" />
<input type="checkbox" id="status_2" name="status_2" value="1" />
<input type="hidden" name="status_3" value="0" />
<input type="checkbox" id="status_3" name="status_3" value="1" />
<input type="submit" />
</form>
<?php
var_dump($_POST);
/*
* checking only the second box outputs:
*
* array (size=3)
'status_1' => string '0' (length=1)
'status_2' => string '1' (length=1)
'status_3' => string '0' (length=1)
*/
Second way - to assign default value for non-set indexes:
<form action="" method="post">
<input type="checkbox" id="status_1" name="status_1" value="1" />
<input type="checkbox" id="status_2" name="status_2" value="1" />
<input type="checkbox" id="status_3" name="status_3" value="1" />
<input type="submit" />
</form>
<?php
for($i = 1; $i<=count($_POST); $i++) {
$_POST["status_$i"] = isset($_POST["status_$i"]) ? $_POST["status_$i"] : 0;
}
var_dump($_POST);
/**
* Here we will be checking only the third checkbox:
*
* array (size=3)
'status_3' => string '1' (length=1)
'status_1' => int 0
'status_2' => int 0
*/
I think adding hidden fields like this will work
<input type="hidden" id="status_1_" name="status_1" value="0">
<input type="checkbox" id="status_1" name="status_1" value="1" />
<input type="hidden" id="status_2_" name="status_2" value="0">
<input type="checkbox" id="status_2" name="status_2" value="1" />
<input type="hidden" id="status_3_" name="status_3" value="0">
<input type="checkbox" id="status_3" name="status_3" value="1" />
I thinks it impossible to get array like what you want from html forms. But this some tricks can be used:
$defaultForm = array(
'status_1' => 0,
'status_2' => 0,
'status_3' => 0,
);
// example array from $_POST
$form = array(
'status_1' => 1,
'status_3' => 1,
);
$form = array_merge($defaultForm, $form);
Result:
array(3) {
'status_1' => int(1)
'status_2' => int(0)
'status_3' => int(1)
}
Try this. If the checkbox is not checked, then the hidden field with the same name will be passed instead.
<form action="" method="post">
<input type="hidden" id="hidden_status_1" name="status_1" value="0" />
<input type="checkbox" id="status_1" name="status_1" value="1" />
<input type="hidden" id="hidden_status_2" name="status_2" value="0" />
<input type="checkbox" id="status_2" name="status_2" value="1" />
<input type="hidden" id="hidden_status_3" name="status_3" value="0" />
<input type="checkbox" id="status_3" name="status_3" value="1" />
</form>
Thanks all. Thank to #RoyalBg give me solution. Like this :
<input type="hidden" name="status_1" value="0" />
<input type="checkbox" id="status_1" name="status_1" value="1" /> Check 1 <br />
<input type="hidden" name="status_2" value="0" />
<input type="checkbox" id="status_2" name="status_2" value="1" /> Check 2 <br />
<input type="hidden" name="status_3" value="0" />
<input type="checkbox" id="status_3" name="status_3" value="1" /> Check 3 <br />
It's work perfectly.. :)
the question may already be answered but i just wanted to take a stab at it...server side only solution:
$p = $_POST;
$a = array();
$a['status_3'] = (int) ($p['status_3'] === 1);
$a['status_2'] = (int) ($p['status_2'] === 1);
$a['status_1'] = (int) ($p['status_1'] === 1);
Testing
// if input is Array("status_1"=>1) output will be
Array ( [status_1] => 1 [status_3] => 0 [status_2] => 0 )
// if input is Array("status_1"=>1, "status_2"=>1) output will be
Array ( [status_1] => 1 [status_3] => 0 [status_2] => 1)
<!--html code-->
<input type="checkbox" name="correct" value="1">Option 1
<input type="checkbox" name="correct" value="2">Option 2
<input type="checkbox" name="correct" value="3">Option 3
<input type="checkbox" name="correct" value="4">Option 4
//php code in function called on form submit
public function addOptions(Request $request)
{
$option = array('1' => 0,'2'=>0,'3'=>0,'4'=>0 );
$option[$request->correct] = 1;
return $option;
}
Why have you taken it in an array?
You can get the unchecked box as 0 by using "isset"
if(!isset($_POST['status_2'])
{
//Set status_2 parameter as 0
}
try below code
$myresult = array();
if(!isset($_POST['status_1'])){
$myresult['status_1'] = 0;
}
if(!isset($_POST['status_2'])){
$myresult['status_2'] = 0;
}
if(!isset($_POST['status_3'])){
$myresult['status_3'] = 0;
}
echo "<pre>";
print_r($myresult);
echo "</pre>";
exit;
Try this one:
for ($i = 1; $i<=3; $i++) {
$_POST["status_$i"] = isset($_POST["status_$i"]) ? $_POST["status_$i"] : 0; // 0 if not set
}
var_dump($_POST);
Assuming we are using checkboxes with zeros or ones...
Using a hidden checkbox with a zero value is just a work-around. Another work around would be to add 0 to the value when receiving the post or get.
Example:
$chkbx1 = $_POST['chckbx1'];
$chkbx1 += 0;
This takes a NULL value an turns it into a zero, but if the value is one, as in its checked, then the value stays the same.
The real issue here isn't inventing a work-around. Its understanding why this is happening. Older versions of mySQL takes null values and converts them into a zero. In newer versions, you must disable strict mode and then a work-around is not needed.

Put checked checkboxes into an array

TO CLARIFY I'VE GOT THE VALUES OF THE CHECKED CHECKBOXES. I NEED TO ORGANIZE THEM IN AN ARRAY SIMILAR TO THE PHP EXAMPLE GIVEN. THANKS
I'm trying to build an array of checked checkboxes to be sent over AJAX for processing by PHP. Originally I got the selected checkboxes by PHP but I'm having trouble converting this process to Javascript.
There are three different groups of checkboxes ('first', 'second', 'third') and for each of these groups there are 4 different checkboxes that can be checked.
The html of the checkboxes followings the same pattern up to value 4.
<input type="checkbox" name="first" class="selection first" value="1" />
<input type="checkbox" name="second" class="selection second" value="1" />
<input type="checkbox" name="third" class="selection third" value="1" />
<input type="checkbox" name="first" class="selection first" value="2" />
<input type="checkbox" name="second" class="selection second" value="2" />
<input type="checkbox" name="third" class="selection third" value="2" />
and so on....
The PHP code would return an array of the checked checkboxes like such.
$selections => array(
['first'] => array(
[0] => 1,
[1] => 3,
[2] => 4),
['second'] => array(
[0] => 2),
['third'] => array(
[0] => 1,
[1] => 4)
);
I've been trying and trying to replicate this in JavaScript but I keep getting errors such as cannot convert undefined to object and the likes. I loop the available positions to create arrays, then loop all the checkboxes and if checked, I get the value.
console.log() prints the position ('first', 'second' or 'third') and the number of the selection (1 - 4). That's all I need, but how do I put this in an array similar to the PHP one?
function getSelections() {
var selections = new Array();
$('.position').each(function() {
selections[$(this).attr('value')] = new Array;
});
$('.selection').each(function() {
if( $(this).prop('checked') == true ) {
position = $(this).attr('name');
selection = $(this).attr('value');
console.log(position + ' - ' + selection);
}
});
return selections;
}
It's to be sent to a PHP script as JSON and I need to decode it as an array like the PHP one.
Nothing fancy needed.... change to this and view the posted arrays.
<input type="checkbox" name="first[]" class="selection first" value="1" />
<input type="checkbox" name="second[]" class="selection second" value="1" />
<input type="checkbox" name="third[]" class="selection third" value="1" />
<input type="checkbox" name="first[]" class="selection first" value="2" />
<input type="checkbox" name="second[]" class="selection second" value="2" />
<input type="checkbox" name="third[]" class="selection third" value="2" />
Then serialize this as normal to submit via ajax instead.
Jquery :checked Selector may help

Categories