I have the following array which can be added to dynamically (multiple categories and multiple questions belonging to that category) but I am struggling on how to add them to my database.
This is an example of how my array can look like:
Array
(
[title] => lijsttitle
[Category name] => Array
(
[0] => Question 1
[1] => Question 2
)
[Category name 2] => Array
(
[0] => Question1
)
)
I remove the title
using array_shift
my code looks like this:
$arr = $_POST['lijst'];
$companyid = $_POST['companyid'];
$store = [];
// pull off first arr element
$title = array_shift($arr);
// save title to store
$store['title'] = $title['name'];
$currCat = '';
foreach($arr as $a) {
$val = $a['value'];
// handle category
if($a['name'] == 'category[]') {
// save cat name
$currCat = $val;
// init questions array
$store[$currCat] = [];
}
else {
// add question to question array
$store[$currCat][] = $val;
}
}
I insert the title of my question list first inside my template
table, but I have two other tables one for my questions and one for my categories.
// Insert template title and companyid
$inserttemplate = '
INSERT INTO templates (title, id_company) VALUES ("'.$conn->real_escape_string($title["value"]).'","'.$conn->real_escape_string($companyid).'")';
$inserttemplatecon = $conn->query($inserttemplate);
I know I can connect those using their id with the last inserted id. But how can I insert all category names into my category
table and the same for questions in my questions
table?
I am not sure how to get those values from my foreach loop.
So first insert a category name and immediately after insert all questions that belong to that category with category_id
being the last inserted id (of the inserted category).
I've tried printing/echoeing multiple variables but I'm not sure how to get the result I need.