How to pass checkbox data through FILTER_SANITIZE in PHP?

Asked

Viewed 62 times

0

I’m not getting past the values of checkbox in PHP. I have a single file home.php with the following code:

<?php
session_start();
ob_start();
include_once("conexao.php");

$btnCadastrar = filter_input(INPUT_POST, 'btnCadastrar', FILTER_SANITIZE_STRING);
if($btnCadastrar){

    $dados_rc = filter_input_array(INPUT_POST, FILTER_DEFAULT);

    $erro = false;

    $dados_st = array_map('strip_tags', $dados_rc);
    $dados = array_map('trim', $dados_st);

    $checkbox = $dados['ch'];
    foreach($checkbox as $id_servico){
        $query = "INSERT INTO os_servico (id_os, id_servico, criado) VALUES (
        '$id_os',
        '$id_servico',
        NOW())";
        $result_query = mysqli_query($conn, $query);
    }

}   
?>

Gives the following errors:

Notice: Undefined index: ch in C:\xampp\htdocs\site2\home.php on line 16
Warnig: Invalid argument supplied for foreach() C:\xampp\htdocs\site2\home.php on line 17

What could be causing the error? is it in the POST passage?

  • 1

    Have you checked the value of $dados and whether there should be ch?

  • ? I don’t get it! I don’t have to have an array of selected checkboxes and call them by ch[]? I can’t see any other way to do it.

  • 1

    Make a var_dump($dados) if you are not using any debug tool (recommended).

  • I did! Result: array(1) { ["btnCadastrar"]=> string(9) "Register" }

  • or when selecting some checkbox: array(2) { ["ch"]=> string(0) "" ["btnCadastrar"]=> string(9) "Register" }

  • 1

    Well, if there’s an index ch in the array, it makes no sense to give the message of Undefined index quoted in the question. But overall the question is confused. What was the expected result when using the function filter_input_array? Why did you use FILTER_DEFAULT?

  • then there is even ch[ ], but note that the string is reset, it is like passing the selection, but not the value.

Show 2 more comments

1 answer

0


Follows the solution:

<?php
session_start();
ob_start();
include_once("conexao.php");

$btnCadastrar = filter_input(INPUT_POST, 'btnCadastrar', FILTER_SANITIZE_STRING);
if($btnCadastrar){

    $checkbox = $_POST['ch'];
    foreach($checkbox as $id_servico){
        $query = "INSERT INTO os_servico (id_os, id_servico, criado) VALUES (
        '$id_os',
        '$id_servico',
        NOW())";
        $result_query = mysqli_query($conn, $query);
    }

}   
?>

Browser other questions tagged

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