Dikshant Ghimire
Dikshant Ghimire

Reputation: 85

Insert multiple HTML data from array multiple input to db using PDO

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

Upvotes: 0

Views: 299

Answers (1)

Asim
Asim

Reputation: 174

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

Upvotes: 3

Related Questions