I'm sending a post request to an end point using while loop to send several values to the "questions" sub-array as seen below but it says "bad request". The body of the data has a sub-array into which I need to send multiple entries fetching from the database. Do I need a foreach loop instead?
$sql= "SELECT * FROM table WHERE quiz_id = $quiz_id";
while ($row_que =mysqli_fetch_array($sql)) {
$question = $row_que['question'];
$marks = $row_que['marks'];
$optionA = $row_que['optionA'];
$optionB = $row_que['optionB'];
$optionC = $row_que['optionC'];
$optionD = $row_que['optionD'];
$optionE = $row_que['optionE'];
$correct_option = $row_que['correct_option'];
$data =
array(
'id' => '2',
'quizName' => 'Third Semester',
'numberOfQuestions' => '10',
'isTimed' => true,
'numberOfMinutesToComplete' => '10',
'targetedClass' => '10',
'subject' => 'English',
'schoolLevel' => 'Grade 1',
'questions' => array(['question' => $question, 'questionMark' => $marks,
'options' => array(['option' => 'A', 'answer'=> $optionA ], ['option' => 'B', 'answer' => $optionB] , ['option' => 'C', 'answer' => $optionC ], ['option' => 'D',
'answer' => $optionD ], ['option' => 'E', 'answer' => $optionE]),
'hasImage' => true,
'images' => array(['images-1' => 'image-1'], ['images-2' => 'image-2']),
'correctionOption' => $correct_option
]),
'totalValidMarks' => '10',
'validUntil' => '20-08-2020'
);
}
// API URL
$url = 'https://my-end-point';
// Create a new cURL resource
$params = $data;
$data_string = json_encode($data);
$curl = curl_init();
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data_string,
CURLOPT_HTTPHEADER => array(
"x-access-token: $token",
"cache-control: no-cache",
"content-type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
// echo $payload;
}
}