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

Asked

Viewed 2,474 times

0

I have two types of checkbox and I need that when selecting one of the two is displayed a field of type input text with the information coming from the database. The field input will be disabled, IE, will be for display only.

Does anyone have a role model for me?
Or any idea how to accomplish that?

  • It seems broad this question, I did not understand if the problem is to recover the data from BD or how to perform the request when the checkbox is selected. Have you done anything? If yes, include the code next to the question and show where you have questions.

5 answers

2

Your question is very generic, yet you can provide the example you want

You need the following steps to accomplish this goal !

  1. Create a javascript monitoring to detect when the checkbox has been enabled or disabled
  2. Access your database without the page loading
  3. Return a text from the database and include a disabled input in screen

So, let’s monitor the checkbox element using Jquery, let’s access a layer that has access to the database using ajax, and let’s use append to include this 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 reply page.php, your case is quite generic, do not know if you are using some kind of drive to access the database or some abstraction of code, Anyway, I believe this might give you an idea of 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;
}
?>

0

You need to be a little clearer.

Take a look: The input you want to display when "checking" a particular checkbox is already filled with the information 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 "checking" the checkbox, then you need to make use of the $.ajax() within the condition if when she returns true.

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

This is an idea and there are others like to use $('#inputTeste').css('display', 'block') to display and $('#inputTeste').css('display', 'none') to hide input text in the context you entered.

  • In my doubt I report that comes information from the database. I do not know if you paid attention. However, I will analyze your question!

  • Sorry, my question was intended to know if the coming of the information was before, when the page was loaded for example, or after/while displayed the input text (in this case, via $.ajax for example). This was not clear in your question. I wondered why it would change the way you would get a more direct answer.

0

Dude I’m trying to do this too. but I want to recover data from 2 tables. for example I have a generic table ação, terro, ficção... and another filme_genero. In other words, they are related and I want to show gender on the screen, and also show checked those who 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 the way it is there, only the first appears of gender and keeps repeating,

0

I don’t do well in Javascript or Ajax yet because I hate their syntax, but PHP I know.

Then follow the Flow :D

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

2º To bring the result of Mysql 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 in an Array (Or vector since we are in a community Br Hu3) (Listadados.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 hand, all the data of your comic book are already cute inside the array $linha[]; to show is just give a echo with the database field 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’s bad Tell me I’m going to get a coffee ;)

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 disabled input data. As an example, display the same input value. Below is the model:

    $('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>
        Tipo 1<input type="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 in jsFiddle.

Browser other questions tagged

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