0

Trying to insert data even if any index of array in foreach loop is empty. trying the following script its giving Undefined index: error in case of empty index.

$data = array();
if(count($_POST['data']) > 0 && !empty ($_POST['data'])){  
    foreach($_POST['data'] as $key => $array){
        $row = array();
        $row['team_id'] = intval($array['team_id']);
        $row['Note'] = strip_tags(trim(strval($array['Note'])));
        $row['result'] = strip_tags(trim(strval($array['result'])));
        $data[$key] = $row;
    }
        $sql = $db->prepare("INSERT INTO teams ('team_id','note','result') values (:team_id, :note, :result) ");

        foreach($data as $key => $array){
           $sql->execute(array(':team_id' => $array['team_id'], ':note' =>$array['Note'], ':result' => $array['result'], ));
    }
}
9
  • Check isset($_POST['data']) and is_array($_POST['data']) first. Commented Sep 19, 2018 at 6:14
  • @arkascha you mean instead of && !empty ($_POST['data']) . Commented Sep 19, 2018 at 6:16
  • No before every index that is unsure you would place isset($array['index']) first Commented Sep 19, 2018 at 6:19
  • Provide the data you are getting from $_POST['data']. Try this if(!empty ($_POST['data'])){ Commented Sep 19, 2018 at 6:19
  • That one does not make any sense anyway after the count($_POST['data']) > 0, does it? It can't be empty if its count is bigger than zero. Commented Sep 19, 2018 at 6:19

2 Answers 2

1

You can prevent isset when set in variable

$row['team_id'] = isset($array['team_id']) ? intval($array['team_id']) : null;
$row['Note'] = isset($array['Note']) ? strip_tags(trim(strval($array['Note']))) : null;
$row['result'] = isset($array['result']) ? strip_tags(trim(strval($array['result']))) : null;
Sign up to request clarification or add additional context in comments.

Comments

1
<?php

$data = array();
foreach ($_POST['data'] as $key => $array) {
    $data[$key]['team_id'] = isset($array['team_id']) ? intval($array['team_id']) : null;
    $data[$key]['Note'] = isset($array['Note']) ? strip_tags(trim(strval($array['Note']))) : null;
    $data[$key]['result'] = isset($array['result']) ? strip_tags(trim(strval($array['result']))) : null;

}

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.