How to select a checkbox and retrieve data in the database?

0

I have 2 types of checkbox and I need to select one of the two to display a field of type input text with the information coming from the database. The input field will be disabled, that is, it will only be displayed.

Does anyone have a blueprint for me? Or any idea how to do this?

    
asked by anonymous 15.02.2015 / 17:32

5 answers

2

Your question is very generic, however, to provide the example you want

You need the following steps to accomplish this goal!

  • Create a monitor with javascript to detect when the checkbox was active or disabled
  • Access your database, without the page loading
  • Return a text from the database and include a disabled input in the screen
  • So let's monitor the checkbox element using Jquery, let's access a layer that has access to the database using ajax, and we'll use append to include it on the screen, see the example!

    Page.html     

        // Monitorando um checkbox com jquery
        $(".checkbox").change(function() {
            // verifica se ele está no estado checked
            if(this.checked) {
                // usando ajax para acessar o servidor
                $.ajax({
                    // Passe alguma coisa via get se necessario
                    url: "resposta.php?param="+this.value,
                    cache: false
                })
                        // buscando o resultado
                        .done(function( texto ) {
                            //usando append para incluir o input no
                            $( "#id" ).append('<input type="text" value="'+texto+'" disabled/>');
                        });
            }
        });
    </script>
    

    To work just return the text on the page answer.php, your case is pretty generic, I do not know if you are using some kind of drive to access the bank or some abstraction of the code, anyway, I believe that it can give you an idea how to implement your code in any other situation!

    <?php
    $hostname = "localhost";
    $username = "userTeste";   
    $password = "passTeste"
    $con = mysql_connect("$hostname", "$username", "$password") or die(mysql_error());
    
    $query = "SELECT * FROM sua_tabela";
    $result = mysql_query($query);
    
    if ( $row = mysql_fetch_assoc ($result){
        echo $row;
    }
    ?>
    
        
    15.02.2015 / 18:01
    0

    You need to be a little clearer.

    Please note: Is the input you want to display when checking a particular checkbox already filled in with the information coming from the database?

    If yes, then:

    $(document).on('change', '#checkBoxTeste', function(){
      if(this.checked){
        $('#inputTeste').slideDown().prop('disabled',true);
      }else{
        $('#inputTeste').slideUp();
      }
    }
    

    Now if the input data needs to be loaded after the checkbox has been checked, you will need to use $.ajax() within the if condition when it returns true .

    If you still prefer, add the disabled inline attribute in the input text, thus avoiding a jQuery ( .prop() ) command and further wiping out your code.

    This is an idea and there are others such as using $('#inputTeste').css('display', 'block') to display and $('#inputTeste').css('display', 'none') to hide the input text in the context in which you reported.

        
    15.02.2015 / 17:58
    0

    As you did not describe how the parameter will be sent to the database, I left an example of how I would do to display the input data disabled. As an example it shows the same input value. The following is the model below:

        $('input[type=text]').hide();
        $('input').change(function(){
            if(this.checked){
              var valor = $(this).val();
              
              $(this).next().val(valor).show();         
            }else{
                
                $(this).next().val('').hide();
            }
    
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>Tipo1<inputtype="checkbox" name="tipo1" id="" value="tipo1"><input type="text" disabled></input><br>
            Tipo 2<input type="checkbox" name="tipo2" id="" value="tipo2"><input type="text" disabled></input><br>

    Example on jsFiddle .

        
    16.02.2015 / 15:14
    0

    I do not handle Javascript or Ajax well because I hate the syntax of them, but PHP I handle.

      

    Then follow the Flow: D

    # 1 Find among our friends Javeiros nerds aii a good solution in Ajax to show or hide the field.

    2nd To bring the MySQL result Come with me "Jeday"

    Connects to db (ConfigDB.php)      

     // definições de host, database, usuário e senha
     $host = "localhost";
     $db   = "seuDb";
     $user = "user";
     $pass = "senha";
     // conecta ao banco de dados (Eu Já uso Mysqli Cowboy) :D
     $con = mysqli_connect($host, $user, $pass, $db) or trigger_error(mysql_error(),E_USER_ERROR); 
     ?>
    

    Now load everything into an Array (or vector since we are in a Br Hu3 community) (DataData.php)

        <?php
        $Checkbox_id = "aqui o id do registro que cê quer puxar";
        //Inclui as credenciais de Conexão
        include ("configBD.php");
        //Define a query
        $query = "SELECT * FROM 'tabela' WHERE ID 'registro_id' = '$Checkbox_id' ";
    
        // executa a query
        $dados = mysqli_query($con, $query) or die(mysqli_error($con));
    
       // transforma os dados em um array
       // Essa Linha Chama o primeiro registro, então na consulta só mostra do segundo valor em diante
       $linha = mysqli_fetch_assoc($dados);
    
    
       /* Essa Linha Reseta as Chamadas para poder exibir do primeiro em Diante Desculpa o POG aí */
      mysqli_data_seek($dados, '0');
    
      // calcula quantos dados retornaram 
      $total = mysqli_num_rows($dados);
    
      ?>
    

    Okay Manolo, you already have the knife and the cheese in your hand, all the data in your BD is already cute inside the array $linha[]; to show just give a echo with the field of the database that you want to display Ex:

        <?=$linha['checkbox_id']?>
        // onde checkbox_id é o nome do campo na tabela mysql
        //vai mostrar o id cadastrado no banco de dados, e assim por diante
    

    Now let's show in HTML (index.php)

        <?php require("listaDados.php");?>
        <!DOCTYPE html>
        <html lang="pt-br">
        <body>
        <?php
          // se o número de resultados for maior que zero, mostra os dados
          while($linha = mysqli_fetch_array($dados)) { 
            ?>
          <input type="checkbox" id="<?=$linha['checkbox_id']?>" value="<?=$linha['checkbox_valor']?>" selected="<?=$linha['checkbox_selecionado']?>" >
        <?php } ?>
        </body>
        </html>
    
      

    If it has been bad, I'll go and get a coffee there;)

        
    16.02.2015 / 03:21
    0

    Dude, I'm trying to do this too. but I want to retrieve data from 2 tables. for example I have a% gen of% table and another ação, terro, ficção... . In other words, they are related and I want to show the genre on the screen, and also to check the ones that are part of this genre

    What would be the best cod to implement. see my cod.

    for($i=0; $i < $numTotal_g; $i++){
        $result_fg = $filmeg->fetch(PDO::FETCH_ASSOC);
        $id_fg = $result_fg['id_genero'];
        $result_g['id'];
        $result_g['nome'];
    ?>  
    <li><input  type="checkbox" name="check[]" id="check[]" 
    
    <?php
    
        if($result_fg['id_genero'] == $result_g['id']){
            echo  'checked';
        } 
    ?>
    

    But as it is there, only the first one of gender appears and keeps repeating,

        
    16.06.2015 / 20:50