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 9101517
In Process

The Archive Base Latest Questions

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

Question: Want to perform a Select Query below (must be this query): SELECT QuestionId

  • 0

Question:

Want to perform a Select Query below (must be this query):

SELECT QuestionId FROM Question WHERE (QuestionNo = ? AND SessionId =
?)

In order to be able to find the QuestionId’s in the Question table and
store it in the Answer Table for all the answers so that we can
determine which answers belong to which question

Problem:

The problem with the mysqli code is that it is not able to insert the correct QuestionId value. It keeps displaying 0 for QuestionId in the Answer Table. So can somebody fix this in order to be able to be able to display the correct QuestionId?

It has to be done the SELECT query provided at top. I have to use that in mysqli.

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();
}

?>
  • 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:09:06+00:00Added an answer on June 17, 2026 at 1:09 am

    You need to retrieve the last value of the sequence used as the autoincrementing id in Question directly after the INSERT – do this using the LAST_INSERT_ID() SQL function. You can then use this value as a parameter when you insert into Answer.

    This is an article on how this may be done.

    You can also restructure your code by eliminating the query for the question id in the insert-answer loop. Instead, when you insert the questions, fill an associative array with the QuestionId for each QuestionNo. While looping over the answers, use the associative array to quickly retrieve the QuestionId. Memory should not be a concert as you currently have all questions and answers in the HTTP request.

    The core of the code will then look like:

    // AA: Declare an empty associative array for QuestionNo -> QuestionID
    $question_ids = array()
    
    for($i = 0;  $i < $c; $i++ )
    {
            // AA: Extract the QuestionNo for multiple use
            $questionNo = $_POST['numQuestion'][$i];
    
            $insert->bind_param("ii", $sessionid, $questionNo);
    
            $insert->execute();
    
            if ($insert->errno)
            {
                // Handle query error here
                echo __LINE__.': '.$insert->error;
                break 1;
            }
    
            // AA: Retrieve the questionId from MySQL
            $questionId = mysql_insert_id();
    
            // AA: Add a key-value pair (QuestionNo, QuestionId) to $question_ids
            $question_ids[$questionNo] = $questionId;
    }
    
    $results = $_POST['value'];
    foreach($results as $id => $value)
    {
        $answer = $value;
    
        // AA: Look up the QuestionId for the question number
        $quesid = $question_ids[$id];
    
        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;
            }
        }
    }
    

    NOTE: I’m not a PHP programmer, and I haven’t tested this, so there may be syntax errors. Sorry 🙁

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using SQLServer 2008 and if I perform the following query: SELECT * FROM
I have a basic query below where it searches a question from the database
Similar Stack Overflow Question I want users to be able to search through my
There are actually 2 question i want to cover in this topic. 1) Is
Well this is a simple question i want to filter two elements sorted reverse
This is an easy question and I want to confirm with you experts! I
This is a more direct question stemming from an earlier more general question i
In a web project I perform a SELECT SQL query against an Indexed column
I asked this question last week on SO- SQL Exclusion Query It looks like
My query currently is: SELECT x, MAX(z) AS mz, y FROM my_table GROUP BY

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.