我如何使用 php 在 sql 数据库的不同列中添加数组元素

How can i add array elements in diferent columns in my sql database using php

我的数组是这样的

Array
(
    [0] => Array
        (
            [questionNumber] => 1
            [question] => Which paper are your preparing for?
            [option] => IELTS General
        )

    [1] => Array
        (
            [questionNumber] => 2
            [question] => How much time do you have at hand to complete your preparation?
            [option] => 1 to 2 months
        )

    [2] => Array
        (
            [questionNumber] => 3
            [question] => Have you taken the IELTS exam earlier?
            [option] => Yes
        )

    [3] => Array
        (
            [questionNumber] => 4
            [question] => How many attempts did you take?
            [option] => 2
        )

    [4] => Array
        (
            [questionNumber] => 5
            [question] => What were your overall band scores
            [option] => 5 to 6 bands
        )

    [5] => Array
        (
            [questionNumber] => 6
            [question] => Which module do you need coaching for?
            [option] => Specific Modules only
        )

)

我的 SQL table 看起来像这样

id | email |    q1 |    a1 |    q2 |    a2 |    q3 |    a3 | q4 |   a4 |    q5 |    a5 |    q6 |    a6

我想将 问题编号 1 问题元素添加到 q1 列并将其选项添加到 a1 列。 类似地添加 问题编号 2 问题元素到 q2 及其选项到 a2 列并重复此过程直到最后一个问题。

我的 php 代码如下

<?php


$servername = 'localhost';
$dbname = 'chartjs';
$username = 'root';
$password = '';

//----------------------------------------------------------Connection Part---------------------------------------------------
$conn = mysqli_connect($servername,  $username, $password, $dbname);
if(!$conn){
    die("Connection Failed". mysqli_connect_error()); 
}



if(isset($_POST["response"])) {

    $responsearray=json_decode($_POST['response'], true);
    print_r($responsearray);
    
    foreach($responsearray as $response){

        $questionNumber =($response['questionNumber']);
        $question =($response['question']);
        $option =($response['option']);
      

     
        $query="INSERT INTO `ielts_quiz_db`(`q1`, `a1`) VALUES (' $question','$option')  ";
    
        
        $result=mysqli_query($conn,$query);
    }
}
?>

您可以使用 for 循环代替 foreach 循环,如下所示

for($i=0;$i<=5;$i++){
 $questionNumber =$responsearray[$i]['questionNumber'];
 $question =$responsearray[$i]['question'];
 $option =$responsearray[$i]['option'];
 
 $num = $i+1;
 
 $query="INSERT INTO `ielts_quiz_db`(q$num, a$num) VALUES (' $question','$option')  ";
}