Return checkbox checked PHP

Asked

Viewed 1,285 times

1

I have this code:

<?php
    $pdo = db_connect();
    $sql = "SELECT * FROM cor_fundo";
    $query = $pdo->prepare($sql);
    $query->execute();
    $option = "";
    $result = $query->fetchAll(PDO::FETCH_ASSOC);
        foreach ($result as $row) {
          $id = $row['cor_fundo_id'];
          $nome = $row['cor_fundo_nome'];
          $option.='<label class="checkbox-inline"><input type="checkbox" name="cor_fundo[]" value="'.$id.'">'.$nome.'</label>';
        }
    echo $option;
?>

He lists the checkbox’s from the database, but I need it to return checked as the customer selected.

Note. It is saved in array in the database.

Example: 3,4,5

  • Have you tried adding the checked in the input? <input type="checkbox" name="cor_fundo[]" value="'.$id.'" checked>

  • if I put it the way you told me... selects all, and not just those who are in the bank

  • 1

    How do you save the option chosen by the user?

  • @Djalmamanfrin writes in a column as array. Ex. dog, cat, rabbit = 3.4.5

  • 1

    This doesn’t seem to make much sense. You’re selecting colors in the database and listing them in the form of checkbox. What column would that be "in array form"?

  • Your MER was not planned correctly. What is the list of client and background tables?

  • In the table "bottom" I have the following columns: cor_bottom and bottom cor_name -- I relation with the table "product" by the following column: bottom product_cor_bottom. --- When I register a product it lists in checkbox the colors (background) that will appear in the product for the customer to buy. --- The site administrator selects the colors and they are saved in the database as an array (3,4,5)

  • 1

    Okay and where’s that amount produto_cor_fundo for you to know which colors are selected? Is it in some variable that you omitted in the question? In fact, edit the question and add this explanation of the last direct comment in the statement. Comment should not be used to give additional information. This only happens if the question is not clear enough.

Show 3 more comments

3 answers

0

If the checkbox marked are in a column in the bank you will have to use the explode.

Example

<?php
    $pdo = db_connect();
    $sql = "SELECT * FROM cor_fundo";
    $query = $pdo->prepare($sql);
    $query->execute();
    $option = "";

    //aqui vc recupera do db o que ele selecionou... (exemplo)
    $usu = $pdo->prepare('SELECT cores_fundo FROM usuario WHERE id=:id_usuario');
    $usu->execute([':id_usuario' => $_SESSION['id_usuario']);
    $usuCor = $usu->fetch();
    $usuCor = explode(",", $usuCor);

    $result = $query->fetchAll(PDO::FETCH_ASSOC);
        foreach ($result as $row) {
          $id = $row['cor_fundo_id'];
          $nome = $row['cor_fundo_nome'];

          //Verificando se esse ID tá marcado pelo usuario
          $marcado = '';
          if(in_array($id, $usuCor))
                $marcado = 'checked';    

          $option.='<label class="checkbox-inline"><input type="checkbox" name="cor_fundo[]" value="'.$id.'" '.$marcado.'>'.$nome.'</label>';
        }
    echo $option;
?>

NOTE: The selects in the user table is to recover the saved colors, I made as an example because I did not have this information in the question. But just make sure it works.

  • Can you explain me this $_SESSION['id_usuario'] ?

  • This is an example of you taking the id of the logged-in user... I don’t know if the case :)

  • I understand, Betinho Silva’s question lacks information :)

0

My code looks like this, but it’s not checking correctly. It’s checking the last 2 only, q has 4 colors

<?php
    $sql = "SELECT * FROM cor_fundo";
    $query = $pdo->prepare($sql);
    $query->execute();
    $result = $query->fetchAll(PDO::FETCH_ASSOC);

        //quantidade de cores na tabela cor_fundo
        $quant = count($result);

        //declaração das variáveis
        for ($k = 0; $k <= $quant; $k++) {
            $item = "z".$k;
            $$item = "";
        }
        $option = "";                                                   

        //consulta das cores/produto selecionado                                                    
        $sql = ("SELECT produto_cor_fundo FROM produto WHERE produto_id = '".$cod."'");          
        $query = $pdo->prepare($sql);
        $query->execute();   
        $result2 = $query->fetchAll(PDO::FETCH_ASSOC);

        foreach ($result2 as $row) {
            $produto_cor_fundo = $row['produto_cor_fundo'];                                                     
        }
        $cores = explode(",", $produto_cor_fundo);
        $contad = count($cores);

       //criação das variaveis dinamicas com o atributo checked para os checkbox do produto
        for ($k = 0; $k < $contad; $k++) {
            $item = "z".$cores[$k];
            $$item = " checked";
        }

        $i=1;
        foreach ($result as $row) {
            $id = $row['cor_fundo_id'];
            $nome = $row['cor_fundo_nome'];
            if (isset($produto_cor_fundo)) {
                $item = "z".$i;
                $option.='<label class="checkbox-inline"><input type="checkbox" name="cor_fundo[]" value="'.$id.'" '.$$item.'>'.$nome.'</label>';
            } else {
                $option.='<label class="checkbox-inline"><input type="checkbox" name="cor_fundo[]" value="'.$id.'">'.$nome.'</label>';
            }
        $i=$i+1;
        }

        echo $option;
        ?>

0

The tables in the example

Table cor_fundo

Tabela cor_fundo

Table produto

Tabela produto

The code is commented.

$pdo = db_connect();
$sql = "SELECT * FROM cor_fundo";
$query = $pdo->prepare($sql);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);

//quantidade de cores na tabela cor_fundo
$quant = count($result);

//declaração das variáveis
for ($k = 0; $k <= $quant; $k++) {
    $item = "z".$k;
    $$item = "";
}
$option = "";
$id="";
$produto_cor_fundo="";
$produto_cor_fundo_novo="";
$userSelecionado="";
$userID="";
$usuarioSel="";
$selec="";

// verificação da possibilidade de update
if ((isset($_POST["cor_fundo"]))&&($_POST["userID"]==$_POST["userID_Old"])) {
    //array das cores selecionadas
    $optionArray = $_POST["cor_fundo"];

    for ($i = 0; $i < count($optionArray); $i++) {
       $produto_cor_fundo_novo=$produto_cor_fundo_novo.$optionArray[$i].",";
    }

    $produto_cor_fundo_novo = substr($produto_cor_fundo_novo,0,-1);

    //condição para que haja update
    if ($produto_cor_fundo_novo!=$_POST["produto_cor_fundoOld"]){
        $id=$_POST["userID"];
        $sql = "UPDATE produto SET produto_cor_fundo='$produto_cor_fundo_novo' WHERE id='$id'";
        $query = $pdo->prepare($sql);
        $query->execute();
    }
}

//consulta das cores/usuario selecionado
if (isset($_POST["userID"])) {
    $id=$_POST["userID"];
    $sql = ("SELECT produto_cor_fundo,usuario FROM produto WHERE id = '".$id."'");          

    $query = $pdo->prepare($sql);
    $query->execute();   
    $result2 = $query->fetchAll(PDO::FETCH_ASSOC);

    foreach ($result2 as $row) {
        $produto_cor_fundo = $row['produto_cor_fundo'];
        $usuarioSel = $row['usuario'];
    }

    $cores = explode(",", $produto_cor_fundo);
    $contad = count($cores);
    $userSelecionado = "Usuario selecionado: ".$usuarioSel;

    //criação das variaveis dinamicas com o atributo checked para os checkbox do usuario
    for ($k = 0; $k < $contad; $k++) {
        $item = "z".$cores[$k];
        $$item = " checked";
    }
}               

$i=1;
foreach ($result as $row) {
    $id = $row['cor_fundo_id'];
    $nome = $row['cor_fundo_nome'];
    if (isset($usuarioSel)) {
        $item = "z".$i;
        $option.='<label class="checkbox-inline"><input type="checkbox" name="cor_fundo[]" value="'.$id.'" '.$$item.'>'.$nome.'</label>';
    }else{
        $option.='<label class="checkbox-inline"><input type="checkbox" name="cor_fundo[]" value="'.$id.'">'.$nome.'</label>';
    }
 $i=$i+1;
 }

//construção do select
$sql = ("SELECT id,usuario FROM produto");
$query = $pdo->prepare($sql);
$query->execute();   
$result3 = $query->fetchAll(PDO::FETCH_ASSOC);

foreach ($result3 as $row) {
    $id = $row['id'];
    $usuario = $row['usuario'];

    if ($usuarioSel==$usuario){
        $selec.="<option value=\"".$id."\" selected>".$usuario."</option>";
    }else{
            $selec.="<option value=\"".$id."\">".$usuario."</option>";
    }
}

echo $userSelecionado;
echo '<br>'; 
echo '<form method="post" action="">'; 
if (isset($_POST["userID"])){
    echo '<input type="hidden" name="userID_Old" value="'.$_POST["userID"].'">'; 
    echo '<input type="hidden" name="produto_cor_fundoOld" value="'.$produto_cor_fundo.'">';
} 
echo "\n"; 
echo $option;
echo "\n";
echo '<br>';
echo '<select name="userID" size="4">';
echo $selec;
echo '</select>';
echo "\n";
echo '<br><button type="submit">Enviar</button>';
echo "\n";
echo '</form>'; 

This solution is based on creating dynamic variables also known as variables or even variables created during PHP execution. In the loop for ($k = 0; $k < $contad; $k++) { through the variables $item create the dynamic variables $$item for each substring contained in the array $cores, which will serve to print the attribute checked in the selected options.

  • I was confused by your code :D

  • It’s confusing everything I said: come on. This page is a product change. Only the site administrator has access. When the administrator changes the product has q appear checked or not the background color of the product, registered in an array the color he has registered.

  • as @Leo Caracciolo did in the display of the tables are ok are the same tables if so we can say, but instead of taking by the user will take by the product

Browser other questions tagged

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