Retrieve checkbox values in an array

Asked

Viewed 1,698 times

3

How can I get the checkbox value in the code below?

It is a presence list and this code I modified to one that I use a little different and this way I do not know how to get the values of checkboxes marked to be able in each name in the table to release the date in each name.

Type I bring the table names and those that are present I mark the checkbox and, when save, the date will be written in each name that is marked.

Follows the code:

<table width="500" border="0"  bordercolor="#B9B3B3" cellspacing=0 cellpadding=2 align="center">
    <tbody>
    <tr align="center">
              <?php
				
		$getfamilia = "SELECT * FROM $tabela";
		$getfamiliaquery = $mysqli->query($getfamilia);
		while($getfamilialine = mysqli_fetch_array($getfamiliaquery)) 
		{ 
			$fn1="Em Andamento";
			$familia = $getfamilialine['nome'];
			$familia_id = $getfamilialine['id'];
			$fn=$getfamilialine['finalizado'];
			if(strcasecmp($fn, $fn1) == 0)
			{
			echo "
			<tr>
					<td width='250' align='center'>$familia </td>
					<td width='250'  align='center'> <input type='checkbox' name='op'></td>
					
					</tr>
			";
			}
		}
		
		echo "</table>"; /*fecha a tabela apos termino de impressão das linhas*/
print_r($mysqli->error);
if($mysqli->connect_errno)
{
	echo"Falha na conexao";
}

else
{
	
}
	?>
    <br>
     <input type="submit" value="SALVAR" />
    </tr>
</tbody>
</table>

  • Kelly, tried to pass the ID value on input: <input type='checkbox' value='$familia_id' name='op'>

  • I had this idea but I did it because I was going to search if I could do it in the value of the checkbox I will see Aki

  • I tried to pick up the id but the update line error pq the id and an array. I did this Aki but I don’t know if it’s right. <? php $name=$_POST['family']; $data=$_POST['date']; $id=$_POST['familia_id']; $table=$_SESSION['table']; if(isset($_REQUEST['op'])) { $item= $_REQUEST['op']; $sql= $mysqli->query("UPDATE $table SET D1 = '$data' WHERE id = $item"); print_r($mysqli->error); } if($mysqli->connect_errno) { echo"Connection failure"; } Else { echo"<script> Alert('Successfully Registered!')</script>"; echo "<script>redirectpage()</script>"; } ?>

  • Kelly, I’ll post an answer.

  • http://answall.com/questions/92898/deletar-apenas-checkbox-selecionados-php/92917#92917

  • I put the code answering my question.... in the table I have the columns D1 to D7 in which have to go the date of presence of who is present. I’ve been stirring but only enter the for. n enters no if. if the quantity is equal to the quantity x inserts the date in the correct column

Show 1 more comment

4 answers

1

First of all, your code needs a few tweaks, I’ll reformat it below. For you to pick up a collection through a post method, you need to treat your inputs as array and capture them in the same way, to do this, I formatted your code as follows:

<?php

if ($mysqli->connect_errno) {
    echo "<pre>Falha na conexão:\n";
       print_r($mysqli->error);
    echo '</pre>'; die();
}

if ($_POST) {
  if (count($_POST['op'])) {
       foreach ($_POST['op'] as $key => $selecionado) {
          $familia_id = $_POST['familia_id'][$key];
          $familia    = $_POST['familia'][$key];
          $status     = $_POST['status'][$key]
          $addFamily  = "INSERT INTO $tabela (id, nome, finalizado)
                         VALUES ('$familia_id','$familia','$status')";
          $addFamilyQueryByStatus = $mysqli->query($addFamily);
      }
  }
  echo "<p>Salvamento processado com sucesso!</p>";
 die();
}

$getfamilia = "SELECT * FROM $tabela where finalizado = 'Em Andamento'";
$getfamiliaquery = $mysqli->query($getfamilia);

 ?> 
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post" name="salvar">
<table width="500" border="0" bordercolor="#B9B3B3" cellspacing="0" cellpadding="2" align="center">
    <tbody>
        <?php
        if ($getfamiliaquery) {
            while ($getfamilialine = mysqli_fetch_array($getfamiliaquery)) { 
               $fn1        = "Em Andamento";
               $familia    = $getfamilialine['nome'];
               $familia_id = $getfamilialine['id'];
               $fn         = $getfamilialine['finalizado'];

                echo "
                 <tr>
                    <td width=\"250\" align=\"center\">{$familia}</td>
                    <td width=\"250\" align=\"center\">
                      <input type=\"checkbox\" name=\"op[]\" value="1">
                      <input type=\"hidden\" value="{$fn}" name=\"status[]\">
                      <input type=\"hidden\" value="{$familia}" name=\"familia[]\">
                      <input type=\"hidden\" value="{$familia_id}" name=\"familia_id[]\">
                    </td>
                </tr>
                ";
            } //fim do loop
        } else {
          echo "<p>Não há dados em andamento para serem processados.</p>";
        }
       //ob: você já fechou a tabela logo abaixo.
    ?>
     <tr>
        <td colspan="2" style="float:right">
          <input type="submit" value="SALVAR" />
       </td>
    </tr>
</tbody>
</table>
</form>

A remark: i would refactor your table by changing the name from "finished" to "status".

1

the code that is on the other page

<?php
$nome=$_POST['familia'];
$data=$_POST['date'];
$id=$_POST['familia_id'];
$tabela=$_SESSION['tabela'];
$qtd=$_SESSION['qtd'];


if($_POST["salvar_ok"]) {
            for($i = 0; $i < count($_POST["op"]); $i++) 
			
			{
               echo"$data";
			   echo"$qtd";
			   
			   
			   
			   
			   if($qtd=="NULL")
			   
			   {
				   
			   
			   $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d1) VALUES('$data')");
			   
			   echo"$data";
	
		       print_r($mysqli->error);
			   
			   }
			   
			   if($qtd=='1')
			   
			   {
				   
			   
			   $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d2) VALUES('$data')");
	
		       print_r($mysqli->error);
			   
			   }
			   if($qtd=='2')
			   
			   {
				   
			   
			   $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d3) VALUES('$data')");
	
		       print_r($mysqli->error);
			   
			   }
			   if($qtd=='3')
			   
			   {
				   
			   
			   $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d4) VALUES('$data')");
	
		       print_r($mysqli->error);
			   
			   }
			   if($qtd=='4')
			   
			   {
				   
			   
			   $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d5) VALUES('$data')");
	
		       print_r($mysqli->error);
			   
			   }
			   if($qtd=='5')
			   
			   {
				   
			   
			   $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d6) VALUES('$data')");
	
		       print_r($mysqli->error);
			   
			   }
			   if($qtd=='6')
			   
			   {
				   
			   $fn="sim";
			   $sql= $mysqli->query(" INSERT IGNORE INTO $tabela (d7, finalizado) VALUES('$data', '$fn')");
			 
		       print_r($mysqli->error);
			   
			   }
			   
			   
            }
        }

if($mysqli->connect_errno)
				{
				echo"Falha na conexao";
				}

			else
				{
	
				
				}



print '<pre>';
var_dump($_SESSION);
print '</pre>';

?>

1

1

Kelly, I just didn’t pass the values to the variables $familia and $familia_id, I did it right away, but make yourself at home.

The concept is exactly the one we talked about, the magic is in value='".$getfamiliaquery["id"]."' name='op[]' value stores the family id in the loop (while), and name stores every loop by mounting indexes that will be rescued via POST so: $_POST['op'][0], $_POST['op'][1], $_POST['op'][2], and so on.

<form action="" method="POST">    
    <table width="500" border="0"  bordercolor="#B9B3B3" cellspacing=0 cellpadding=2 align="center">
        <tbody>
            <tr align="center">
            <?php

            $getfamilia = "SELECT * FROM $tabela";
            $getfamiliaquery = $mysqli->query($getfamilia);

            while($getfamilialine = mysqli_fetch_array($getfamiliaquery)) {
                if($getfamilialine["finalizado"] == "Em Andamento") {
                    echo "
                        <tr>
                            <td width='250' align='center'>".$getfamilialine["nome"]."</td>
                            <td width='250' align='center'><input type='checkbox' value='".$getfamilialine["id"]."' name='op[]'></td>
                        </tr>";
                }
            }

            echo "</table>";
            ?>
            <br />
            <input type="submit" name="salvar_ok" value="SALVAR" />
            </tr>
        </tbody>
    </table>
    <br />
    <?php
        // Aqui imprime o resultado retornado via POST
        if($_POST["salvar_ok"]) { // Se clicar no botão SALVAR executa o bloco abaixo
            for($i = 0; $i < count($_POST["op"]); $i++) { // Loop enquanto houver conteúdo na array
                echo $_POST["op"][$i]."<br />"; // $_POST["op"][0], $_POST["op"][1], $_POST["op"][2], $_POST["op"][3]........ 
            }
        }
    ?>
</form>
  • that part Aki <td width='250' align='center'>". $getfamiliaquery["name"]." </td> <td width='250' align='center'><input type='checkbox' value='". $getfamiliaquery["id"]." 'name='op[]'></td> </tr>"; had to take it out the way you did and leave it my way so the name and chekbox didn’t appear. , which shows in for i played on another page q is q executes all the database and tals...

  • I changed and you are not registering in the bank for what I do not know. I could not test on my pc for localhost do not know but the page n opens right for me. I played on a server q is where I put the site however speaks q register but when I pull the data has nothing but I can’t access the server to see my table.... but I’ll be trying Aki anything I put

  • Sorry Kelly, as I had to simulate your database to test the code, I reversed the rsrsrs variables. I corrected the code in the answer. Sorry.

  • i am not able to enter the data in the database by for. my registration calls one the other page q is the one who makes the entry in the database. it enters the for but does not enter the conditions to compare and make the insertion but if I put an echo it shows the q ta in the variable.

  • Can you add to your reply the code content of the other page that does the Insert/update in the database? Then it will be easier to help you.

  • @Kellycris saw the rest of the code he posted. I now believe I no longer understand the objective. What I could understand is that first the form (checkbox) is listed from an SQL query in your BD, so what I understood you want to do is just an UPDATE in the status, kind of "In Progress" to "Finished", it wouldn’t be that?

  • would be the end of treatment but I already solved the registration problem is already working.

Show 2 more comments

Browser other questions tagged

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