Capturing the boolean value of a checkbox in PHP

Question:

I'm making a product form, where the user needs to inform if the product is used or not, but I'm having difficulties in capturing the value of this checkbox , if it is 1 or 0 , in mysql the column is already set to boolean with default 0

logic-add-product.php

 <?php
    include("conecta.php");

    #Variáveis para cadastrar
    $nome = $_POST["nome-produto"];
    $preco = $_POST["preco-produto"];

    $descricao = $_POST["descricao-produto"];

    #Caso de verificação da variável booleana
    $usado = $_POST["usado-produto"];
    if(array_key_exists($usado, $_POST)) {
        $usado = "true";
    }else{
        $usado = "false";
    }

    #Query de inserção
    $query = "insert into produtos(nome, preco, descricao, usado) values('{$nome}', '{$preco}', '{$descricao}', {$usado})";

    #Variável para executar a inserção
    $retornoInsercao = mysqli_query($conexao, $query);

    #Teste para verificar inserção
    if($retornoInsercao){
        header("Location:index.php");
        die();
    }else{

    };

?>

add-products.php

<?php
    include("header.php");
    include("conecta.php");
?>

 <form action="logica-adiciona-produto.php" method="post">
    <fieldset>
        <label>Nome:</label>
        <input type="text" name="nome-produto">
        <label>Preço:</label>
        <input type="number" name="preco-produto">
    </fieldset>
    <fieldset>
        <label>Usado ?</label>
        <input type="checkbox" name="usado-produto" value="true">
        <label>Categoria:</label>
        <select name="">

        </select>
        <label>Descricao:</label>
        <textarea name="descricao-produto"></textarea>
    </fieldset>
    <fieldset>
        <input type="submit">
    </fieldset>
 </form>

Answer:

Your code is wrong, you are sending a variable that does not match the key name, please note:

Change:

#Caso de verificação da variável booleana
$usado = $_POST["usado-produto"];
if(array_key_exists($usado, $_POST)) {
    $usado = "true";
}else{
    $usado = "false";
}

that's why:

$usado = array_key_exists('usado-produto', $_POST) ? 1 : 0;

Explanation:

The structure of the array_key_exists function

bool array_key_exists ( mixed $key , array $array )

where the first parameter is the name of the key to be searched inside the array and the second the array itself, which returns true ( true ) or false ( false ) in the result, if found or not…

or also

$usado = isset($_POST['usado-produto']) ? 1 : 0;

Referencia: array_key_exists

Scroll to Top