0

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.

Neik0
  • 93
  • 2
  • 8
  • 1
    there is a } missing for the first question loop, and you should use $surveyquestionid = $con->lastInsertId(); – nbk May 22 '20 at 22:51
  • How exactly would i do that? – Neik0 May 22 '20 at 23:51
  • insteat of the hle Select statement to get the id of course see https://stackoverflow.com/a/10680965/5193536 , but you still didn't add the missing } – nbk May 23 '20 at 00:06
  • Yes I added that back. I got this error now. Fatal error: Uncaught Error: Call to undefined method mysqli::lastInsertId() – Neik0 May 23 '20 at 00:41
  • you have to use the mysqli version of if see https://www.php.net/manual/en/mysqli.insert-id.php – nbk May 23 '20 at 07:38

0 Answers0