0

I have multiple FAQ fields (question and answer) and have to insert them into the MySQL database. I am using PDO.

HTML:

<input type="text" name="qns[]/>
   <textarea name="ans[]"></textarea><br>

PHP

    $qns=$_POST['qns'];
    $ans=$_POST['ans'];
    date_default_timezone_set('Asia/Kathmandu');
    $created= date('m/d/Y h:i:s a', time());

    foreach ($qns as $q){
        foreach ($ans as $a){
                $stmt=$pdo->prepare("INSERT INTO tbl_faq 
                            (faq_qn, faq_ans, faq_creator, faq_created, faq_updated)
                            VALUES
                            (?,?,?,?,?)");
                $stmt->bindValue(1, $q);
                $stmt->bindValue(2, $a);
                $stmt->bindValue(3, $_SESSION['id']);
                $stmt->bindValue(4, $created);
                $stmt->bindValue(5, $created);
                $stmt->execute();
        }
  }
  header("location:dashboard.php?page=faq/view.php");

When I insert it into the db, it produce the Cartesian Product. I know there is something going on with the loop. But not sure how to fix it..

db screenshot

4
  • What's your specific question about this? What have you tried to resolve the problem? Commented Jul 7, 2021 at 7:36
  • How do the answers relate to the questions. You just seem to get 2 arrays from the $_POST array and combine them. Commented Jul 7, 2021 at 7:43
  • I am trying to insert the question and answer into separate columns of a database tabel. Commented Jul 7, 2021 at 7:48
  • 1
    the size of questions and answers is same right, just use 1 array and same key. You are actually doing Cartesian product as you are using nested loop. Commented Jul 7, 2021 at 7:51

1 Answer 1

3

Use only one loop and pass the index of question loop in $ans[]

foreach ($qns as $key => $q)
{
    $stmt = $pdo->prepare("INSERT INTO tbl_faq 
                (faq_qn, faq_ans, faq_creator, faq_created, faq_updated)
                VALUES
                (?,?,?,?,?)");

    $stmt->bindValue(1, $q);
    $stmt->bindValue(2, $ans[$key]);
    $stmt->bindValue(3, $_SESSION['id']);
    $stmt->bindValue(4, $created);
    $stmt->bindValue(5, $created);
    $stmt->execute();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.