Store several variables (or an array) in the same field (MySQL) [closed]

0

Can someone tell me what would be the best option to store the following data?

The user (within a form) has the possibility to select multiple checkboxes (19), and I need to store if they are marked or not (all of them) in a single field.

I could use an Array, but I do not know how to store it in the database. And if you can, I would like to see an example, since in the PHP ofilical page I do not understand the use.

Thank you very much.

    
asked by ByBrayanYT - Tops y más 09.10.2018 в 19:40
source

2 answers

2

Another possibility is that when you save the corresponding form, those checkboxes arrive as an array in your PHP controller and save them as a json string. Then, when you read it from bbdd, you convert it back to an array. The indices that you have defined will be the ones you have checked.

if you can get an array to your controller like this:

$checks = $_POST['checkboxes'];

and when you print that array you have formed it as:

[ 
'check1' => true, 
'check4' => true,
'check9' => true
]

Then you could turn it into json with:

$checksEnBBDD = json_encode($checks, true);

When you go to read them from bbdd, you use json_decode:

$checks = json_decode($checkEnBBDD, true);
    
answered by 09.10.2018 / 22:20
source
1

To store several variables in a field you can use xml or json, for example this script is part of an event that I call to retrieve the data of a survey with its respective value that goes from 1 to 5:

  $(document).ready(function() {
      $("#btn").click(function() {
          var valores = "<xml>";
            $(".pregunta").each(function() {
                valores +='<row><P>'+$(this).prop("id")+'</P>'
                +'<R>'+$(this).find('input[type=radio]:checked').attr('value')+'</R></row>'
             });
        valores = valores+"</xml>";
        document.cookie = "resultados = " + valores;
      });

I save them in a cookie and then process them in php where I save all the answers in a value field NVARCHAR (MAX) in xml format, this file is created by going through each element that has the class "question" with jquery and recover the value of the attribute.

This could give you an idea of how to do it, if you show me how structured your page is, it could possibly be more precise when orienting you.

Greetings

    
answered by 09.10.2018 в 22:03