error entering data in php database

0

I'm doing a page in html with the checkboxes to insert into string form inside a table row, but if I do not mark all the options it gives an error (but inserts into the bank), how do I get rid of this error if in case I choose only one value from the checkbox?

  

Notice: Undefined index: plastic in C: \ xampp \ htdocs \ TCC \ postage.php on line 4
  Notice: Undefined index: papelao in C: \ xampp \ htdocs \ TCC \ postage.php on line 5

include_once("setting.php");
$plastico = $_POST ['plastico'];
$papelao = $_POST ['papelao'];
$metal = $_POST['metal'];
$madeira = $_POST['madeira'];
$vidro = $_POST['vidro'];

$array = array ($plastico, $papelao, $metal, $madeira, $vidro);

foreach ($array as $key => $valor) {
    $campo[]= $valor;
    //echo $campo."<br/>";
}
$teste = implode(',',$campo);

 try{
  $sql = "INSERT INTO postagens (descricao) VALUES ('$teste')";
  echo $sql;
  $res = mysqli_query($conn, $sql);
  $linhas = mysqli_affected_rows($conn);

    if ($linhas ==1){
        echo "registro gravado com sucesso";
    }else{
        echo "falha na gravaçao";
    }
    
asked by anonymous 26.08.2017 / 18:26

3 answers

0

Since vars are non-existent, for example 0, you can do the following: check if they exist and if not, set them to 0, this error occurs because you are trying to get a post that does not exist

if (isset($_POST['opcao'])) 
     $var = $_POST['opcao']; else
     $var = 0;

so, if it does not have a value, it will be 0

    
26.08.2017 / 20:25
0

Your error refers to the space between $ _POST and the brackets for these 2 indexes, change

$plastico = $_POST ['plastico']; por $plastico = $_POST['plastico'];
$papelao = $_POST ['papelao']; por $papelao = $_POST['papelao'];
    
02.02.2018 / 10:32
0
  

This type of Notice: Undefined index: warning is caused because you tried to call a $ _POST variable that was not sent through the form.

With this scheme only those that are marked will return

HTML

put all name of checkbox as material[] . These brackets treat elements of the same name as an array

<form id="myForm" action="" method="post">
    <input type="checkbox" name="material[]" value="plastico" />plastico<br>
    <input type="checkbox" name="material[]" value="papelao" />papelao<br>
    <input type="checkbox" name="material[]" value="metal" />metal<br>
    <input type="checkbox" name="material[]" value="madeira" />madeira<br>
     <input type="checkbox" name="material[]" value="vidro" />vidro<br>
    <input type="submit" value="Enviar">
</form>

PHP

if ((isset($_POST["material"])) && (!empty($_POST["material"]))){
    $opcoes = $_POST["material"];
    $materiais = implode( ",", $_POST['material'] );

    echo $materiais;

// ....
//..... "INSERT INTO postagens (descricao) VALUES ('$materiais')";


}
    
26.08.2017 / 21:58