I am inserting answer of each of my questions I need to get the question id and inserted into the answer table

see my code

<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" id="quiz" class="container width_648">

<?php
            $getTheQuiz = $db->prepare("SELECT * FROM rec_employer_quiz WHERE ad_id=?");
            $getTheQuiz->bind_param('i', $ad);
            if ($getTheQuiz->execute()) {
                $res = $getTheQuiz->get_result();
                $i = 0;
                while ($q = $res->fetch_array()) {
                    ?>
                    <div class="oneLine">
                        <div class="question">
                            <h3><?php printf("%s", $q['question']) ?></h3>
                            <input type="hidden" value="<?php printf("%s", $q['id']) ?>" name="qid" id="qid">
                        </div>
                        <div class="answer">
                            <input type="hidden" name="qid" id="qid" value="<?php printf("%s", $q['id']) ?>">
                            <textarea name="answer[]" rows="3" maxlength="200" class="message1 width_640"></textarea>
                        </div>
                    </div>
                <?php
                }
                ?>
                <div class=" oneLine">
                    <input type="submit" name="ans" id="ans" value="I'm Finished" class=" MainBtn">
                </div>

                <?php
                $dateApplied = date(date_default_timezone_get());
                if (isset($_POST['ans'])) {
                    //$questionId=$_POST['qid'];
                    foreach ($_POST["answer"] as $key => $answer) {
                        $questionId=$_POST['qid'];
                        $answer = $_POST["answer"][$key];
                        $putData = $db->prepare("INSERT INTO rec_employer_quiz_results (id, uid, ad_id, qid, answer, exam_date)VALUE(?, ?, ?, ?, ?, FROM_UNIXTIME(?))");
                        $putData->bind_param('iiiiss', $id, $uid, $ad, $questionId, $answer, $dateApplied);
                        if ($putData->execute()) {
                            echo "done";
                        } else {
                            printf("Error: %s\n", $db->error);
                        }
                    }
                }
            }
            ?>
        </form>

What I am getting now is the last question id for all the answers I need to insert the id of the question with it's value.

edit
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" id="quiz" class="container width_648">


        <?php
        $getTheQuiz = $db->prepare("SELECT * FROM rec_employer_quiz WHERE ad_id=?");
        $getTheQuiz->bind_param('i', $ad);
        if ($getTheQuiz->execute()) {
            $res = $getTheQuiz->get_result();
            while ($q = $res->fetch_array()) {
                ?>
                <div class="oneLine">
                    <div class="question">
                        <input type="hidden" name="qid[<?php printf("%s", $q['id']) ?>]" value="qid[<?php printf("%s", $q['id']) ?>]">
                        <h3><?php printf("%s", $q['question'])?></h3>
                    </div>
                    <div class="answer">
                        <label for="answer"></label>
                        <textarea name="answer[]" id="answer" rows="3" maxlength="200" class="message1 width_640"></textarea>
                    </div>
                </div>
            <?php
            }
            ?>
            <div class=" oneLine">
                <input type="submit" name="ans" id="ans" value="I'm Finished" class=" MainBtn">
            </div>


            <?php
            $dateApplied = date(date_default_timezone_get());
            if (isset($_POST['ans'])) {
                $questionId = $_POST['qid'];
                foreach ($_POST["answer"] as $key => $answer) {
                    $answer = $_POST["answer"][$key];
                    $putData = $db->prepare("INSERT INTO rec_employer_quiz_results (id, uid, ad_id, qid, answer, exam_date)VALUE(?, ?, ?, ?, ?, FROM_UNIXTIME(?))");
                    $putData->bind_param('iiiiss', $id, $uid, $ad, $questionId, $answer, $dateApplied);
                    if ($putData->execute()) {
                        print_r($_POST);
                    } else {
                        printf("Error: %s\n", $db->error);
                    }
                }
            }
        }
        ?>
    </form>

still can't get the right qid

can any one help please

Dani AI

Generated

Your POST shows the classic problem: every question used the same non-array input name for qid, so each new hidden field overwrote the previous one and only the last ID arrived in $_POST. Two simple, reliable fixes:

Option A — make the answers keyed by question id (recommended). Give each textarea a name that includes the question id so PHP receives an associative array keyed by qid:

<textarea name="answer[<?php echo $q['id']; ?>]"></textarea>

Then handle them as:

if (isset($_POST['ans'])) {
    $stmt = $db->prepare(
      "INSERT INTO rec_employer_quiz_results (uid, ad_id, qid, answer, exam_date) VALUES (?, ?, ?, ?, NOW())"
    );
    foreach ($_POST['answer'] as $qid => $answer) {
        $qid = (int) $qid;
        $answer = trim($answer);
        if ($answer === '') continue;
        $stmt->bind_param('iiis', $uid, $ad, $qid, $answer);
        $stmt->execute();
    }
    $stmt->close();
}

Option B — keep parallel indexed arrays. Output a hidden qid[] and answer[], then match by index:

<input type="hidden" name="qid[]" value="<?php echo $q['id']; ?>" />
<textarea name="answer[]"></textarea>
foreach ($_POST['answer'] as $i => $ans) {
    $qid = (int) $_POST['qid'][$i];
    $answer = trim($ans);
    // insert using $qid and $answer
}

Notes and cautions: prepare the INSERT once (not inside a loop) for performance; cast qid to int; skip empty answers; prefer NOW() in SQL (or pass time() if you want FROM_UNIXTIME(?)). Also avoid manually inserting an id column if it is auto-increment — let the database assign it. This will stop the single-last-qid behavior you saw and ensure each answer is stored with its correct question id.

I am getting this on print_r($_POST);

Array
(
    [qid] => 26
    [answer] => Array
        (
            [0] => this is anset
            [1] => saldjhaskl
            [2] => lkjklj
            [3] => lkjlkjlkj
            [4] => lkjlkjbh
            [5] => ,mbn
            [6] => ,mb,
            [7] => mnk
            [8] => hkl
            [9] => lkjhlkjl
        )

    [ans] => I'm Finished
)
1

Array
(
    [qid] => 26
    [answer] => Array
        (
            [0] => this is anset
            [1] => saldjhaskl
            [2] => lkjklj
            [3] => lkjlkjlkj
            [4] => lkjlkjbh
            [5] => ,mbn
            [6] => ,mb,
            [7] => mnk
            [8] => hkl
            [9] => lkjhlkjl
        )

    [ans] => I'm Finished
)
1

Array
(
    [qid] => 26
    [answer] => Array
        (
            [0] => this is anset
            [1] => saldjhaskl
            [2] => lkjklj
            [3] => lkjlkjlkj
            [4] => lkjlkjbh
            [5] => ,mbn
            [6] => ,mb,
            [7] => mnk
            [8] => hkl
            [9] => lkjhlkjl
        )

    [ans] => I'm Finished
)
1

Array
(
    [qid] => 26
    [answer] => Array
        (
            [0] => this is anset
            [1] => saldjhaskl
            [2] => lkjklj
            [3] => lkjlkjlkj
            [4] => lkjlkjbh
            [5] => ,mbn
            [6] => ,mb,
            [7] => mnk
            [8] => hkl
            [9] => lkjhlkjl
        )

    [ans] => I'm Finished
)
1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.