PHP MySQL insert values from multiple checkboxes into one column in table - php

I have a form that a user would fill out while creating a ticket for a bug they have found on our website. In the form there is currently an input field where the user would enter in the designs that the bug is affecting (ex., "Design1, Design2, Design3, Design4" ...etc). When the form is submitted the value is stored in a table column named affectedDesigns.
What i am wanting to do is create several checkboxes (one check box for each design we have) that a user would select instead of using the input field. They would be able to select all that apply. If possible i would still like to store all of the values into the affectedDesigns column in one record. I'm thinking that i can gather the selected checkboxes values and create an array or some comma delimited value that contains all of the selected items and submit that to the databasein the one record in the affectedDesigns column. How can i achieve this?
Also, how would i then pull that data and re-populate the checkboxes if they would like to go back later and edit the ticket? Thanks for any help!

I would avoid to store all values within a single field. You'll have a lot of problems once you'll have to do some query because you violate normalization rules.

create an array from your $_POST values keyed on the name of each checkbox, then just serialize that array before insert.... then you can unserialize it when you load it up again

You'll end up using explode() and implode() to convert between string and array.

You need the same answer I'm looking for.
Sprites in Basic language used that system for you to select the bits you wanted ON or OFF for each column (3 cols each sprite: 24 bites), and the sum of all the 8 values gives exactly the unique value that only that combination of elements on/off can give.
The KEY is that each elements adds a value that always is greater than ALL the other previous values added up together.
I.g. Checkboxes values are 1, 2, 4, 8, 16, 32, 64, 128.
E.g. If 3rd and 5th elements are selected (values 4 + 16) the result, 20, will only be obtained by those elements, since the next value 32 is greater than the sum itself and even if you sum up all the values up to the 5th element (value 16) the result will never reach 32 (it will always be 1 less than the next possible value, in this case adds up 31)
Basic language used to do it automatically, and it was easy since the max value was fixed. Each sum was only 8 values long. You need a maximum value to be input to your function to limit the attempts the script would make to "try".
So, THIS is what you need, I just don't know the name.
As soon as I find the name of this technique / math operation I'll post a working function here.
You could also get a binary number with the options, e.g. 01001001011 and then just use the character position to figure out whether that checkbox is on or off.
PS. What kind of answer is "you'll end up using explode or implode"?? That's the answer of the lazy fortune reader. "you'll eat and bleep until you die" :S

Lazy solution: assuming nothing else depends on the IDs of entries in affectedDesigns, just delete all entries for that ticket, then re-enter the submitted $_POST values.

The answer was right in the binary option.
It happens to be that a decimal number converted to binary, gives you EXACTLY the combination of options you need. Ones for the "selected" option and Ceroes for the options not selected (read right to left)
So the trick to save them is easy.
Assign each checkbox a value of 2^index, where index is your checkbox id/order
… and you'll get
2^index0 = 1
2^index1 = 2
2^index2 = 4
2^index3 = 8
…and so on.
Then, you sum up your checkbox values, let's say
$options_dec = sum($_POST['options']); //outputs 5 if options 0 and 2 are selected
That decimal sum, converted to binary shows you exactly which checkboxes were selected:
$options_bin = base_convert ( $options_dec, 10, 2 ); //outputs 0101 (reads right to left)
Now you can convert it to an array, reverse it, and call each matching its index with your checkboxes.
$options_arr = array_reverse( str_split( $options_bin, 1 ) ); //returns array containing "0,1,0,1"
Now populate your checkboxes with a loop. Assuming the checkboxes come in the same order than stored values, and each have a 2^$i.
for($i = 0; $i < sizeof($options_arr); ++$i) {
$checkbox_value = pow ( 2 , $i );
$checked_val = ( $options_arr[$i] ? 'checked' : '');
echo "<input type='checkbox' value='$checkbox_value' $checked_val />\n";
}
Not tested, since I made my version in JavaScript.
Another solution is to grab the option right from the binary string
$checked_val = (boolean) substr( $options_bin , -($i+1), 1 );// +1 because neg substr counts from 1, not 0

If being human readable in the database is not important you could use the PHP serialize function to combine all the rows into one storable string object.
If you want the data in the database to be readable, you could use implode/explode to convert your array to a single string and store as is in a char datatype.
Or if you want the data to be more managable and be able to do queries on it, I would store the checkboxes using the mysql SET datatype rather than a string.

Related

how to create Dynamic Input value with two different datatype time and text and insert into one single column

I have Dynamic Input box with Time Input and Text Input I want to show as a list items and also wanted to insert values in one column of table in SQL
example :
09.30 PM Saturday night journey begins.
01.30 AM We Reach the Base village
02:00 AM Some Yumm, Breakfast!
How to add multiple input for list item with two different datatype time and text ??
you are getting into complex code, make two different Varible/text Input/columns
if you still want use them add something in between and use Sting function like : strlen() / stripos() / stristr() ---- and while using it in code make two different variables
example value [startTime09.30 PM - ReachTime 10.00AM]
Get Lenth of Text strlen() [44Charecters] >> find position of "-" stripos("-")[23rd postion] >> Chop strings left part and store it in variable do same with remaining

Is it safe to search through serialized array as a string? (MySql query)

I have a serialized array like this
a:6:{i:0;i:6;i:1;i:65;i:2;i:56;i:3;i:87;i:4;i:48;i:5;i:528;}
For example i want to make a mysql query like this
$id_serialize = 6;
"SELECT id FROM table WHERE col LIKE '% i:" . $id_serialize . "; %'"
Is it possible to get a conflict (for example the numbers are repeated etc.) as a consequence of this query ?
Is there another more effective and correct way to find number in array without unserializing the array and without looping ?
It depends on data you are going to store. For integers it is highly possible.
a:6:{i:0;i:6;i:1;i:65;i:2;i:56;i:3;i:87;i:4;i:48;i:5;i:528;}
This actually menas:
a:6:{...} - array of 6 elements
i:0;i:6; - first element, id 0, value 6
i:1;i:65; - second element, id 1, value 65
and so on
If you will get to array of 7 elements, 7th element definition would be: i:6;i:34 And this would collide with i:0;i:6;. Your query would return results with id 6 along with results with value 6.
A bit more about arrays anatomy http://www.php.net/manual/pl/function.serialize.php#66147
a:1:{i:0;s:5:"i:42;";}
Oops.
It's extremely hard to search within data formats which allow arbitrary content. It's the same reason why regexen are simply unsuited for (X|HT)ML. You should really be normalising the data and store each value in its own column/row.
If you are certain of the contents of the array - that is, if you know that all the items in the array are numbers - you should be able to use your method without too much trouble. If anything else makes it into the array you may start getting false results.

PHP, find exact value from mysql arranged data

I have a data in My-Sql column like this
T_interest
1,14,49,145,203,302
It represents each value for personal interest keywords.
I tried to extract the value and distinguish whether it has the value or not for the checkbox.
if(strstr($u_interest['u_interest'], ','.$row['i_idx'])):
$selected = 'checked';
here is the php command that I use right now.
but it doesn't extract exact value from the database.
Let's say I want to check if the data has 14 number or from this user table
T_interest
1,14,49,145,203,302
and if I use above command it tells me that a user has two values.
14,145
It looks like PHP strstr command tells me two values because these two have 14 number.
So, can you help me why this is happening?
If you want more php lines I can post them.
Explode it into an array, this way you get the individual values.
explode(",",$t_interest["u_interest"]);
Then you can test for equality much easier.
You really need to read up on database normalization. A properly normalized design would make this problem moot.
As for your question, since you're forced to use string operations, you'll have to check for multiple different cases:
1) the number you want is at the START of the string
2) the number you want is at the END of the string
3) the number you want is the ONLY number in the string
4) the number you want is in the MIDDLE of thee string:
SELECT ...
WHERE
(T_Interest = 14) OR // only number
(T_Interest LIKE '14,%') OR /// at the begnning
(T_Interest LIKE '%,14') OR // at the end
(T_Insertest LIKE '%,14,%') // in the middle

PHP: Compare two sets of numbers, no dupes

I'm creating a lottery contest for my site, and I need to know the easiest way to compare numbers, so that no two people can choose the same numbers. It's 7 sets of numbers, each number is a number between 1 and 30.
For example, if user 1 chooses: 1, 7, 9, 17, 22, 25, 29 how can I make sure that user 2 can't choose those same exact number?
I was thinking about throwing all 7 numbers into an array, sort it so the numbers are in order, then join them into one string. Then when another user chooses their 7 numbers, it does the same, then compares the two. Is there a better way of doing it?
What you describe sounds like the best way to me, IF you are dealing with all submissions in the same script - I would trim(implode(',',$array)) the sorted array, store the resulting string in an array and call in_array() to determine whether the value already exists.
HOWEVER I suspect that what you are actually doing is storing the selections in a database table and comparing later submissions against this table. In this case (I am taking a liberty and assuming MySQL here but I would say it is the most common engine used with PHP) you should create a table with 7 columns choice_1, choice_2 ... choice_7(along with whatever other columns you want) and create a unique index across all seven choice_* columns. This means that when you try and insert a duplicate row, the query will fail. This lets MySQL do all the work for you.
Try array_diff. There are some really good examples on php.net.

Eliminating Repetition in a Randomized Matrix

I am writing a program that involves placing one number into each cell of a 7x7 grid. There are 56 numbers, chosen from at random, and there must be no repetition.
The end result should be a 7x7 grid in which each cell contains an integer from 1 to 56, with no two cells containing the same number. What is the most efficient way of doing this?
extra words:
I tried creating a for x{for y{}} that would go through the grid cell by cell and add a random number 1-56. It would then check a 56-slot array to see if that number was already in use, and correspondingly either re-roll or accept the number, then flag the array to mark the number as in use. For some reason, I couldn't get it to work, and it seemed like a bad solution. I scrapped it, and instead had a second for x{for y{}} run each time and check the entire grid cell by cell for the rolled number before approving or rejecting it. This also didn't quite work and seemed unwieldly, so I scrapped it as well.
You can generate an array of 1:56, then shuffle, then pick out the first 49 elements.
$arr = range(1,56);
shuffle($arr);
$vals = array_slice($arr, 0, 49); //49 because grid is 7x7
// put $vals in grid.
Create an array of length 56, filled with numbers 1 to 56
Use Fisher-Yates shuffle to create an unbiased, randomised array
Fill 7x7 matrix (row or column order) sequentially from array.
Create an array of 56 elements containing the numbers 1 to 56.
Generate a random number between 1 and the length of the array
Choose the number at that index and remove it from the array
lather, rinse, repeat
Create an array with all the numbers needed, and shuffle it.
$fullGrid = range($min, $max);
shuffle($fullGrid);
Now all you need to do is visually display the $fullGrid array.
More on the php shuffle function.

Categories