Notice Error: Undefined index: [closed]

0

The following code:

<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/tecnliv/core/init.php';
$padreID = (int)$_POST['padreID'];
$selected = sanitize($_POST['selected']);

$childQuery = $db->query("SELECT * FROM 'categorias' WHERE padre = '$padreID' ORDER BY nombre");

ob_start(); ?>
 <option value =""></option>
 <?php while($child = mysqli_fetch_assoc($childQuery)): ?>
 <option value="<?=$child['id'];?>" <?=(($selected == $child['id'] )?' lected':'');?>><?=$child['nombre'];?></option>
 <?php endwhile; ?>

<?php echo ob_get_clean(); ?> 

Return the error:

  

Notice: Undefined index: parentID in C: \ xampp \ htdocs \ tecnliv \ admin \ parsers \ child_categories.php on line 3

     

Notice: Undefined index: selected in C: \ xampp \ htdocs \ tecnliv \ admin \ parsers \ child_categories.php on line 4

    
asked by Salvador Fernandez 30.08.2017 в 06:17
source

1 answer

1

These NOTICE appear because the indicated variables are not defined, in this case it is because those variables were not sent per POST .

You can validate if data were received or not in the following way:

<?php
if ( !empty($_POST['padreID']) OR !empty($_POST['selected']) ) {
  // se recibieron datos POST
  $padreID = (int)$_POST['padreID'];
  $selected = sanitize($_POST['selected']);
}
else{
    // NO se recibieron datos POST
    echo 'NO se recibieron datos POST';
    // detenemos la ejecución
    exit;
}

Instead of cutting the execution you could also declare default values when data is not received and continue execution, depending on what you need:

<?php
if ( !empty($_POST['padreID']) OR !empty($_POST['selected']) ) {
    // se recibieron datos POST
    $padreID = (int)$_POST['padreID'];
    $selected = sanitize($_POST['selected']);
}
else{
    // NO se recibieron datos POST
    // asignamos valores por defecto
    $padreID = 1;
    $selected = 'lo que sea';
}
    
answered by 30.08.2017 в 11:25