Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9102159
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T01:18:46+00:00 2026-06-17T01:18:46+00:00

I am having trouble being able to insert QuestionId into the Answer Table. The

  • 0

I am having trouble being able to insert QuestionId into the Answer Table.

The Question inserts with no problem, but I am trying to retrieve the QuestionId from the Question Table which is an auto increment into the Answer Table by finding the SessionId and QuestionNo that particular QuestionId belongs to. Instead it keeps displaying 0 for QuestionId when inserted into Answer Table.

Now I know the query which tries to perform the select for each QuestionId from the Question Table is correct as this has been tested. I think the problem is where I have placed my code but I am not sure?

Here are the db tables:

Question Table

QuestionId (auto)  SessionId  QuestionNo
4                  2          1
5                  2          2
6                  2          3

Answer Table at moment:

AnswerId (auto)  QuestionId  Answer
7                0           A
8                0           C
9                0           A
10               0           B
11               0           True

What Answer Table should look like:

AnswerId (auto)  QuestionId  Answer
7                4           A
8                4           C
9                5           A
10               5           B
11               6           True

Below is the code:

 $questionsql = "INSERT INTO Question (SessionId, QuestionNo) 
    VALUES (?, ?)";
if (!$insert = $mysqli->prepare($questionsql)) {
    // Handle errors with prepare operation here
    echo __LINE__.': '.$mysqli->error;
}

 $answersql = "INSERT INTO Answer (QuestionId, Answer) 
    VALUES (?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
    // Handle errors with prepare operation here
    echo __LINE__.': '.$mysqli->error;
}



//make sure both prepared statements succeeded before proceeding
if( $insert && $insertanswer)
{
    $sessid =  $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
    $c = count($_POST['numQuestion']);

    for($i = 0;  $i < $c; $i++ )
    {


            $insert->bind_param("ii", $sessionid, $_POST['numQuestion'][$i]);

            $insert->execute();

            if ($insert->errno) 
            {
                // Handle query error here
                echo __LINE__.': '.$insert->error;
                break 1;
            }
}

        $results = $_POST['value'];
        foreach($results as $id => $value) 
        {
            $answer = $value;

            $lastID = $id;

            $questionidquery = "SELECT QuestionId FROM Question WHERE (QuestionNo = ? AND SessionId = ?)";

        if (!$questionidstmt = $mysqli->prepare($questionidquery)) {
        // Handle errors with prepare operation here
          echo __LINE__.': '.$mysqli->error;
        }


        // Bind parameter for statement
        $questionidstmt->bind_param("ii", $lastID, $sessionId);

        // Execute the statement
        $questionidstmt->execute();

                    if ($questionidstmt->errno) 
                    {
                        // Handle query error here
                        echo __LINE__.': '.$questionidstmt->error;
                        break 2;
                    }

        // This is what matters. With MySQLi you have to bind result fields to
        // variables before calling fetch()
        $questionidstmt->bind_result($quesid);

        // This populates $optionid
        $questionidstmt->fetch(); 

        $questionidstmt->close(); 



            foreach($value as $answer) 
            {
                $insertanswer->bind_param("is", $quesid, $answer);

                $insertanswer->execute();

                if ($insertanswer->errno) {
                    // Handle query error here
                    echo __LINE__.': '.$insertanswer->error;
                    break 3;
                }
            }
        }


    //close your statements at the end


    $insertanswer->close();
    $insert->close();
}

?>

UPDATE:

Results from var_dump($_POST);

array(8) { 
["numberAnswer"]=> array(2) { 
         [0]=> string(1) "1" 
         [1]=> string(1) "1" 
         } 
         ["numQuestion"]=> array(2) 
         { 
         [0]=> string(1) "1" 
         [1]=> string(1) "2" 
         } 
         ["questionText"]=> array(2) { 
         [0]=> string(12) "What is 2+2?" 
         [1]=> string(12) "What is 4+4?" 
         } 
         ["gridValues"]=> array(2) { 
         [0]=> string(1) "4" 
         [1]=> string(1) "4" 
         } 
         ["reply"]=> array(2) { 
         [0]=> string(6) "single" 
         [1]=> string(6) "single" 
         } 
         ["textWeight"]=> array(2) { 
         [0]=> string(1) "5" 
         [1]=> string(1) "5" 
         } 
         ["submitDetails"]=> string(14) "Submit Details" ["value"]=> array(2) { 
         [1]=> array(1) { 
         [0]=> string(1) "B" 
         } 
         [2]=> array(1) { 
         [0]=> string(1) "D" 
         } 
         } 
         } 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T01:18:48+00:00Added an answer on June 17, 2026 at 1:18 am

    Right now your QuestionID is coming from $_POST['value'], which is probably not what you want… you need to get the automatically generated QuestionID from mysql after each question is inserted.

    You can retrieve the last generated ID using $mysqli->insert_id. Do this after each call to $insert->execute();, then use those IDs when you go to insert your answers.

    Edit 1:

    You should be using $mysqli->insert_id, because insert_id is only valid on a connection object (yours is called $mysqli).

    You also need to assign the insert_id to something. I’m having trouble following your code but I think what you want is to store question IDs in an array for later use, something like this:

    $question_ids[$i] = $mysqli->insert_id
    

    I’m at a loss for what you’re trying to do after this, I guess you pull in some answers with a corresponding question number but… perhaps if you can post the output of var_dump($_POST) we will understand a bit better. In any case you will need some kind of a loop that inserts the answers for each question, and you can (hopefully) use the array $question_ids[$i] to retrieve the QuestionIDs.

    Edit 2:

    Here is some sample code (untested), try to get this working before getting fancy with $_POST and $_SESSION

    <?php
    $questions = array(
        array(2, 1),
        array(2, 2),
        # etc
    );
    $answers = array(
        array(A, C),
        array(A, B),
    );
    
    $questionsql = "INSERT INTO Question (SessionId, QuestionNo) VALUES (?, ?)";  
    if (!$insert = $mysqli->prepare($questionsql)) {
        die('couldn\'t prepare statement 1');
    }
    
    $answersql = "INSERT INTO Answer (QuestionId, Answer) VALUES (?, ?)";
    if (!$insertanswer = $mysqli->prepare($answersql)) {
        die('couldn\'t prepare statement 2');
    }
    
    $c = count($questions);
    
    for($i = 0;  $i < $c; $i++)
    {
        $insert->bind_param("ii", $questions[$i][0], $questions[$i][1]);
        $insert->execute();
    
        if ($insert->errno) 
        {
            die("Error inserting question $i");
        }
    
        $lastID = $mysqli->insert_id;
    
        foreach ($ans in $answers[$i])
        {
            $insertanswer->bind_param("is", $lastID, $ans);
    
            $insertanswer->execute();
    
            if ($insertanswer->errno) {
                die("Error inserting answer to question $i");
            }
        }
    
    }
    
    $insertanswer->close();
    $insert->close();
    ?>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am having trouble being able to programatically add elements to an observable array
I'm having trouble with MVC4 not being able to bind to anything. For Example:
I'm having trouble being able to see objects I've created when I have enabled
I am trying to build a self-hosted PHP site, but I am having trouble
i'm having trouble with AWeber's not-being-able-to-format-rss-pubDate failure when creating a blog broadcast template, and
Im having trouble understanding class relationships after being asked to research it further, would
I am having trouble finding out why my iAd is not being removed after
I'm having trouble the same instance of a C# class being used in multiple
I'm having trouble handling the scenario whereby an event is being raised to a
Being fairly new to programming, I am having trouble understanding exactly what Homebrew does...

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.