On my site, I have multiple checkbox fields, where each input doubles in value from the previous, like this:
<form name=test>
<input type='checkbox' name='groupe' value = '1'>
<input type='checkbox' name='groupe' value = '2'>
<input type='checkbox' name='groupe' value = '4'>
<input type='checkbox' name='groupe' value = '8'>
<input type='checkbox' name='groupe' value = '16'>
etc...
</form>
I stock the fields selected (by the user) result in summing all of the values selected.
Let's say that the user had selected 4 and 1. In this case, I insert the sum of field values, which is 5. At this stage, after insert, my SQL table is:
test
5
I need to retrieve the values selected to create this result number 5.
The information to do that are: - 31 (the max result, which is the sum of each field 1+2+4+8+16) - it is impossible to get a result value of 5 using 2+2+1, because an input cannot be selected twice;
I did a lot of searching to solve this, but I couldn't find anything helpful. How do I do this in SQL or PHP?
I'm not sure what the point of storing the sum and then recovering the individual values - why not store the separate values?
That said, if you must, the algorithm is quite simple:
<?php
print_r(get_parts($argv[1]));
function get_parts($number) {
$res = array();
for ($pow = 1; $pow <= 16; $pow <<= 1)
{
if ($pow & $number) {
array_push($res, $pow);
}
}
return $res;
}
?>
This function will accept a number and return an array of the components:
$ php test.php 5
Array
(
[0] => 1
[1] => 4
)
$ php test.php 31
Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 8
[4] => 16
)
If you decompose your final number in binary, since it is sum of power of two, each bit will correspond to one check box.
You can use then bitwise operator to check of those bits are set.
http://php.net/manual/en/language.operators.bitwise.php
Example :
if ($groupe & 4) {
//if bit 000100 was set
}
I'm not sure if this is what you're looking for but basically, the way your read the state of an input form element in PHP is by looking at the $_POST
special global variable.
Ideally, each checkbox would have a unique name. That way you could be certain which checkbox you are reading. If you have multiple elements with the same name, they will be passed on as an array, most likely in the order they are rendered on the page.
So, to read the values for your check boxes you would use this:
$checkboxes = $_POST['groupe'];
$finalValue = 0;
if(isset($checkboxes)) // make sure you are getting something back
{
if (is_array($checkboxes)) // make sure you are getting back an array
{ // since you have multiple elements named groupe
foreach($checkboxes as $value) {
$finalValue += $value;
}
}
}