Okay so I have an html document where you can type add questions and on to the questions you can add possible answers. Then you can save it to a mysql database. Here is the current code that runs.
$surveyname = $_POST['surveyname'];
$question = $_POST['question'];
$answers = $_POST['answer'];
$stmt1 = $con->prepare('INSERT INTO surveygroup (userid,surveyname) VALUES (?, ?)');
$stmt1->bind_param('is', $_SESSION['id'], $surveyname);
$stmt1->execute();
$stmt2 = $con->prepare('SELECT id FROM surveygroup WHERE surveyname=?');
$stmt2->bind_param('s', $surveyname);
$stmt2 -> execute();
$stmt2 -> store_result();
$stmt2 -> bind_result($surveygroupid);
$stmt2->fetch();
foreach ($question as $val) {
$stmt3 = $con->prepare('INSERT INTO surveyquestion (surveyid,question) VALUES (?, ?)');
$stmt3->bind_param('is', $surveygroupid, $val);
$stmt3->execute();
$stmt4 = $con->prepare('SELECT id FROM surveyquestion WHERE question=?');
$stmt4->bind_param('s', $val);
$stmt4 -> execute();
$stmt4 -> store_result();
$stmt4 -> bind_result($surveyquestionid);
$stmt4->fetch();
}
foreach ($answers as $val) {
$stmt5 = $con->prepare('INSERT INTO surveyanswers (surveygroupid,surveyquestonid, answer) VALUES (?, ?, ?)');
$stmt5->bind_param('iis', $surveygroupid, $surveyquestionid, $val);
$stmt5->execute();
}
So the question variable is an array that gets looped through and each question is added with a different id. Then the answers are added. The problem with this code is that in the mysql database it does not add in the ID correctly. It addds in the last one. for example it saves like this.
tblsurveyquestions
id || surveyid || question
1 || 1 || How old are you?
2 || 1 || How tall are you?
tblsurveyanswers
id || surveygroupid || surveyquestonid || answer
1 || 1 || 2 || 50+
2 || 1 || 2 || 70+
3 || 1 || 2 || Short
4 || 1 || 2 || Tall
So as you can see it takes the last id of every single question and it applies to all the answers.