I need to insert 2 choices ($choices
) and 2 categories ($categories
), which are linked to the question that was last inserted by the Question_ID
. The question inserts fine. However, the choices and categories don't. The arrays both contain the all the data that is needed. I need each choice to be inserted at the same time as their related category ID as these are needed at another point on the site and each choice must relate to a specific Category_ID
.
UPDATE - I added an if statement inside the inner foreach loop which will continue the loop if the statement executes and if it doesn't then error will get echoed. The error was echoed. How can I fix this?
PHP Code:
<?php
session_start();
include_once 'DBConnection.php';
if(isset ($_POST['Question']) && isset($_POST['Category_ID1']) && isset($_POST['Category_ID2']) && isset($_POST['Choice1']) && isset($_POST['Choice2'])) {
//get post variable
$question = $_POST['Question'];
//category array
$categories = array();
$categories[0] = $_POST['Category_ID1'];
$categories[1] = $_POST['Category_ID2'];
//Choices array
$choices = array();
$choices[0] = $_POST['Choice1'];
$choices[1] = $_POST['Choice2'];
//Insert question query
$stmt = mysqli_prepare($conn, "INSERT INTO Questions (Question) VALUES ('?')");
mysqli_stmt_bind_param($stmt, 's',$question_p);
$question_p = $question;
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_num_rows($stmt);
$id = mysqli_insert_id($conn);
if ($result) {
foreach ($choices as $choice) {
if ($choice != '') {
//Choice query
foreach ($categories as $category) {
if ($category != '') {
$query = "INSERT INTO Choices(Choice, Question_ID, Category_ID) VALUES ('$choice', '$id', '$category')";
$results = $conn->query($query);
if($results){
continue;
}else{
echo "error";
}
}
}
}
}
} else {
echo $conn->error;
}
}else{
echo "Not Set";
}