Retrieve dynamically generated checkbox values

Asked

Viewed 117 times

1

I have a form that has some checkboxes with city names that are generated dynamically by PHP. I’d like to know how to get these values and what kind of structure to store them (Array?) and what kind of data to save in Mysql. These checkboxes will be selected at the time of the user’s registration and should give the same permissions to access data from that particular city. So, any suggestions? Thanks to anyone who can help me.

Here is the registration form code

<div class="container-fluid">
<div class="panel panel-primary">
    <div class="panel-heading">
        CADASTRAR USUÁRIO
    </div><br>

    <div id="filtros" style="padding-left: 20px">
        <a id="voltar_pagina" href="menu.php" class="btn btn-primary" title="Voltar ao início">
            <span class="glyphicon glyphicon-home"></span>
        </a>
        <a id="voltar_lista" href="javascript:history.back()" class="btn btn-primary" title="Voltar">
            <span class="glyphicon glyphicon-chevron-left"></span>
        </a>                        
    </div>

    <div class="panel-body">

        <form id="form_cad_usuario" data-toggle="validator" class="form-horizontal" method="POST" action="../config/usuario/processa_cad_usuario.php">

            <!--DADOS DO USUÁRIO-->
            <div class="page-header">
                <h4>Dados do Usuário</h4s>
                <hr>
            </div>


            <div class="form-group">                 
                <label for="status_check" class="col-sm-2 control-label">Ativo</label>
                <div class="col-sm-10">
                    <div class="checkbox">
                        <label>
                            <input id="status_check" name="status_check" type="checkbox" value="ativo" checked>
                        </label>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label for="nome_usuario" class="col-sm-2 control-label">Nome</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="nome_usuario" name="nome_usuario" placeholder="Nome" data-error="Por favor, informe o nome completo para o usuário." required>
                    <div class="help-block with-errors"></div>
                </div>
            </div>

            <!--DADOS DE ACESSO-->
            <div class="page-header">
                <h4>Dados de Acesso</h4>
                <hr>
            </div>

            <div class="form-group">
                <label for="login_usuario" class="col-sm-2 control-label">Usuário</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="login_usuario" name="login_usuario" placeholder="Usuário" data-error="Por favor, digite um nome para o usuário." required>
                    <div class="help-block with-errors"></div>
                </div>
            </div>

            <div class="form-group">
                <label for="senha_usuario" class="col-sm-2 control-label">Senha</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" id="senha_usuario" name="senha_usuario" placeholder="Senha" data-error="Por favor, digite um senha para o usuário." required>
                    <div class="help-block with-errors"></div>
                </div>
            </div>

            <div class="form-group">
                <label for="permissao_usuario" class="col-sm-2 control-label">Senha</label>
                <div class="col-sm-10">
                    <select class="form-control" id="permissao_usuario" name="permissao_usuario" data-error="Por favor, selecione um nível de permissão para o usuário." required>
                        <option value="4">Jogos</option>
                        <option value="3">Regional</option>
                        <option value="2">Administrador</option>
                        <option value="1">Master</option>
                    </select>
                    <div class="help-block with-errors"></div>
                </div>
            </div>

            <!--DADOS DA  REGIONAL-->
            <div class="page-header">
                <h4>Regionais Permitidas</h4>
                <hr>
            </div>

            <?php
            $resultado = lista_regionais();

            while ($registro = mysqli_fetch_assoc($resultado)) 
            {
                $id_regional = $registro['id'];
                $nome_regional = $registro['nome'];

            ?>

            <div class="col-sm-2">
                <div class="form-group">
                    <div class="col-sm-1">
                        <div class="checkbox">
                            <label>
                                <label class="col-md-10" for="<?php echo"regional_$id_regional" ?>">
                                    <input type="checkbox" name="<?php echo"regional[$id_regional]"; ?>" id="<?php echo"regional_$id_regional" ?>" value="<?php echo $nome_regional; ?>"> 
                                    <small><?php echo $nome_regional; ?></small>
                                </label>
                            </label>
                        </div>
                    </div>
                </div>
            </div>

            <?php
            }
            ?>

            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button id="botao_salvar" type="submit" class="btn btn-primary pull-right">Salvar <span class="glyphicon glyphicon-floppy-save"></span></button>
                </div>
            </div>

        </form>
    </div>
</div>

Here is the code of the class that processes the registration

<?php
session_start();

include_once ('../seguranca.php');
include_once ('../../dao/usuario_dao.php');

verifica_acesso();

$nome = $_POST['nome_usuario'];
$login = $_POST['login_usuario'];
$senha = $_POST['senha_usuario'];
$permissao_str = $_POST['permissao_usuario'];
$check_status = $_POST['status_check'];

//Verifica o status recebido
if(!strcmp($check_status, "ativo"))
{
    $flag_ativo = 1;
}

//Verifica a permissão recebida
if(!strcmp($permissao_str, "4"))
{
    $permissao = 4;
}
else if(!strcmp($permissao_str, "3"))
{
    $permissao = 3;
}
else if(!strcmp($permissao_str, "2"))
{
    $permissao = 2;
}
else if(!strcmp($permissao_str, "1"))
{
    $permissao = 1;
}

var_dump($permissao);

//cadastra_usuario($nome, $login, $senha, $permissao, $flag_ativo, $modificado);

As a beginner I also accept suggestions to improve the structure of the code and the way everything is being done. I thank you already.

1 answer

1


In PHP you get the values of a multiple checkbox the same way you get a normal checkbox. The difference is that it returns an array.

In your case, if you print the variable $_POST['regional'], will notice that it is an array.

$regional = $_POST['regional'];
print_r($regional);

Regarding the storage in the Mysql database, I suggest creating a table that will be responsible for associating each user’s regionals. Example of structure:

CREATE TABLE usuario_regional (
  `id_usuario` int, 
  `id_regional` int
);

With this, when registering the user (insert in your user table), you should also insert in this table (usuario_regional) each region the user is associated with. Example:

-- associada o usuário com ID=1 as regionais com ID=1, ID=2 e ID=3
INSERT INTO usuario_regional (`id_usuario`, `id_regional`)
VALUES (1, 1),
       (1, 2),
       (1, 3);
  • I really appreciate you taking the time to answer me. Correct me if I’m wrong but this relationship between user and regional characterizes a Mxn relationship, don’t you? I’m somewhat layman in the database and I’m trying to learn as needed. Could you please exemplify a query where I insert the user into the database and also enter the regional data into that table? If it is not too much abuse I would also like to see how to recover from the bank the cities to which the user "x" has access. Thank you immensely. Hug!

  • This is a many-to-many relationship (https://pt.wikipedia.org/wiki/N_para_N).

  • You need to do two query`s to perform this routine: one to insert the user into the user table and one to insert into the relationship table (as I illustrated in the answer above). As in your code you call a function called "cadastra_usuario", I believe you already have in this function a query to insert the user in the user table, so just add the query you insert in the "usuario_regional" relationship table. Tip: Use the PHP "mysqli_insert_id" function to get the ID of the entered user.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.